error: cannot convert value of type 'String' to expected argument type 'Character' - swift

I am running into this error using Swift 4. I'm attempting to get the index of an element in an array.
if removedLetters.contains(selectedLetter!) {
print("\(selectedLetter!) is in the word")
print(theWordArray.index(of: "\(selectedLetter)"))
}
results in error: cannot convert value of type 'String' to expected argument type 'Character'
I also tried creating a character variable var selectedChar:Character = selectedLetter but I get a conversion error: error: cannot convert value of type 'String?' to specified type 'Character'

You can convert a String to a Character by accessing the first letter if you are confident that selectedLetter is one letter.
if removedLetters.contains(selectedLetter!) {
print("\(selectedLetter!) is in the word")
print(theWordArray.index(of: "\(theWordArray[selectedLetter!.first!])")
}
If it is more than one letter, your code will crash though, so do some validating first.

Related

When I convert string to int it shows The argument type 'String? [duplicate]

This question already has answers here:
"The argument type 'String?' can't be assigned to the parameter type 'String'" when using stdin.readLineSync()
(3 answers)
Closed 12 months ago.
int item = int.parse(stdin.readLineSync());
"Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't."
I didn't know what this want to mean, I just want to convert a string that I will type into integer
I'm using VScode with Dart extension
Thanks for your attention
The error is caused by the null safety feature in Dart, see https://dart.dev/null-safety.
int.Parse() requires a non-null string. While std.readLineSync() is of a nullable string type.
If you check that the user gave input, you can confirm that the value is not null.
Something like:
if(item ==null){
print("empty input not allowed");
}
else{
int item = int.parse(stdin.ReadLineSync());
print(item);
}
You can also use tryParse instead.
var itemInt = int.tryParse(item ?? "");
Use this
int item = int.parse(stdin.readLineSync()??"0");
instead of this
int item = int.parse(stdin.readLineSync());
here in the image you can see readLineSync return String? not String
so the chance of reading input string may be non string value or emptyline .so we cant convert to number.

What is the difference between a `String x = expr` and `var x = expr as String`?

While developing a Flutter app, I ran into a problem where out of two seemingly similar things, only one really works. The other gives an error.
// this does NOT work
// gives error: E/flutter (13080): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception:
// type 'MaterialPageRoute<dynamic>' is not a subtype of type 'Route<String>?' in type cast
onButtonPress() async {
String ret = await Navigator.of(context).pushNamed("/page");
print(ret);
}
// this works !
onButtonPress() async {
var ret = await Navigator.of(context).pushNamed("/page") as String;
print(ret);
}
Both looks like doing the same thing - casting the value returned from the route into a String. But why does only one of them works ?
As your error states:
// gives error: E/flutter (13080): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception:
// type 'MaterialPageRoute<dynamic>' is not a subtype of type 'Route<String>?' in type cast
onButtonPress() async {
String ret = await Navigator.of(context).pushNamed("/page");
print(ret);
}
You are trying to assign a MaterialPageRoute<dynamic!> to a Route<String!>.
This is a simple case of type mismatching.
In the other example that you have posted, you are using var instead of String. This allows you to assign every type that you want to it.
await Navigator.of(context).pushNamed("/page") returns a future, which is not a string.
the scope of a var is just a generic variable that can be anything upon assignation.
When you assign a variable as String X , that means you tell the program specifically that - I am sure that the value I am going to get will be String and I want it to be stored in X . If the value returned is not String type it will throw an error.
When you assign the variable as var X , that means you are telling the program that I am not sure what will be the type of value which will be returned but I want the returned value to be returned as 'String ' (so even if you get any response as int or double or anything else it will try to use the complete value returned as string) . So var helps in getting rid of type errors when you are not sure of the type , but it's always best practice to know what type you are getting and define accordingly.

Swift - Binary operator '>=' cannot be applied to operands of type 'String' and 'Int'

Not really understanding why this isn't working. I'm pretty new to the Swift world.
The error I'm getting is Binary operator '>=' cannot be applied to operands of type 'String' and 'Int'
Could anyone help me understand why I'm getting this error? Do I need to convert the String to a Double or is there something else I'm totally missing? Again I'm new to Swift.
Do I need to convert the String to a Double?
Yes, that's basically it.
You must declare first a variable to accumulate all the inputs:
var inputs = [Double]()
Observe that I'm declaring an array of Double because that's what we are interested in.
Then, each time you ask the input, convert the obtained String to Double and store it in your array:
print("Please enter a temperature\t", terminator: "")
var message : String = readLine()!
let value : Double = Double(message)!
inputs.append(value)
Finally, check all the accumulated values in inputs (you got this part right):
for value in inputs {
// value is already a Double
if value >= 80 {
message = "hot!"
}
// etc.
}
I suggest researching how to convert to Double with error checking (i.e. how to detect "100 hot!" and ignore it because can't be converted).
Also, consider using a loop to read the values.

How to fix 'Int' is not convertible to 'String' in a comparison that uses only Int?

Imagine my surprise that this Swift code generates an error in Xcode 6.1.1:
public func unlockNextLevel() -> Int
{
var highest : Int = 123
return (highest < highestUnlockedLevel)
}
More precisely, it tells me that in the return line:
'Int' is not convertible to 'String'
So, since I had some of these weird conversion errors before, I thought I'll try converting both types to Int and see what I get:
public func unlockNextLevel() -> Int
{
var highest : Int = 123
return (Int(highest) < Int(highestUnlockedLevel))
}
I then get the following error on the return line:
Could not find an overload for '<' that accepts the supplied arguments
But when I break it down to just constant values:
return (Int(3) < Int(12))
I get the int not convertible to string error again.
'Int' is not convertible to 'String'
Gnnnnn.... oh-kay, so I give it another shot without the brackets:
return highest < highestUnlockedLevel
This then gives me yet another error message:
Cannot invoke '<' with an argument list of type '(#lvalue Int, #lvalue Int)'
Okay, I get it Swift, I'm stoopid. Or maybe ... hmmm, take this, Swift:
var result = highest < highestUnlockedLevel
return result
Arrrr ... nope. Swift decides that now the return line constitutes yet another error:
'Bool' is not convertible to 'Int'
(... dials number for psych evaluation ...)
So ... could someone explain to me:
how to fix or work around this issue?
and of course: Why?? Oh, why???
Note: This is in a mixed Objc/Swift project if that makes any difference. The highestUnlockedLevel variable is declared in a Swift class with custom setter and getter.
(highest < highestUnlockedLevel) produces Bool not Int (unlike Objective-C where it returns int that can be automatically converted to BOOL), thats why you get the error. But certainly its wrong and misleading error as the problem is that Bool cannot be converted to Int.

'inout String' is not convertible to 'UnsafePointer<String>'

I am using a function that takes an UnsafePointer<String>.
How do I get an UnsafePointer<String> from a String?
Trying &someString gives me the error:
'inout String' is not convertible to 'UnsafePointer<String>'
&someString creates a CMutablePointer<String>.
To convert it to an UnsafePointer, the simplest solution is to call the special function:
withUnsafePointer(&someString) { unsafePointer in
//do something with the unsafePointer
}