Cannot invoke initializer for type 'Int' with an argument list of type JSON - ios

Why I cannot convert String value from the JSON response to Int? It returns me the next error:
Cannot invoke initializer for type 'Int' with an argument list of type '(JSON)'
When I try to:
Int(json[i]["id"])
How can I convert it to Int?

I assume you're using SwiftyJSON.
In that case you have two options:
The optional getter:
if let id = json[i]["id"].int {
// do something
}
The non optional getter:
let id: Int = json[i]["id"].intValue

Related

'String?' can not convert to 'String' in dart

A value of type 'String?' can't be assigned to a variable of type 'String'.
Try changing the type of the variable, or casting the right-hand type to 'String'.
This error message i got when i run this code.
This is a simple user input code on dart.
var person = ['abc', 'qwe', 'dfg'];
stdout.write('Enter Index : ');
String p = stdin.readLineSync(); //Error
int per = int.parse(p);
per > person.length
? stderr.write('Index does not exist')
: stdout.write('Person ${person[per]}');
}
Seems like readLineSync() returns nullable type. But you declare variable p as non-nullable. Either declare p as nullable: String? instead of String or make readLineSync() return default value if null:
String p = stdin.readLineSync() ?? "";// will return empty String if method readLineSync() returns null.
First of all check the null safety documentation, you'll learn everything you need to know
https://dart.dev/null-safety/understanding-null-safety
readLineSync returns a value of Type String? Meaning the return value must be a nullable String.
p is of type String and therefore expects a String (not a nullable String). the trick here is to cast stdin.readLineSync() to String:
String p = stdin.readLineSync() as String;
String p = stdin.readLineSync()!; #shorthand syntax
On top of that, your code needs some improvements. What if p can't be cast into an integer? One way to handle this is to add a try block and catch any FormatException.

Trying to work with an enum that has duplicate values in Swift

I have an enum of type String which needs to have multiple variables that have the same value. My enum looks something like this:
class MyClass {
enum MyEnum: String {
case blahA = "blaha"
case blahB = "blahb"
...
static var blahD = "blah"
static var blahE = "blah"
}
}
The reason why I'm using static var's in the above construction is because both "blahD" and "blahE" need to reference the same String value, used in different places (don't ask me why, it just has to be this way). However, I have a method where I need to pass in the value of the enum as follows:
if let testString = myString(foo: MyEnum.blahD) {...}
I unfortunately am getting the following compilation error:
Cannot convert value of type "String" to expected argument type "MyClass.MyEnum".
How do I get around passing the above variable which has duplicate values in my enum in the method, but cast it to the type of "MyClass.MyEnum"?
You can do this if you make the extra case reference the other enum case directly instead of just assigning them the same string value:
class MyClass {
enum MyEnum: String {
case blahA = "blaha"
case blahB = "blahb"
...
case blahD = "blah"
static var blahE = MyEnum.blahD
}
}
Then you can pass MyEnum.blahE the same way you would pass MyEnum.blahD
If the function takes a value of type MyEnum, you cannot do this. The type properties blahD and blahE are simply not of that type. Only the cases of the enum are of type MyEnum.
The function parameter's type must be changed to String.
The only other way around it would be to add a case to the enum that has a raw value matching the value of those two properties: case blahDOrE = "blah". Then you could construct that case: MyEnum(rawValue: MyEnum.blahD), but I can't see that being very useful.

Why print() is printing my String as an optional?

I have a dictionary and I want to use some of its values as a key for another dictionary:
let key: String = String(dictionary["anotherKey"])
here, dictionary["anotherKey"] is 42 but when I print key in the debugger I see the following:
(lldb) expression print(key)
Optional(42)
How is that possible? To my understanding, the String() constructor does not return an optional (and the compiler does not complain when I write let key: String instead of let key: String?). Can someone explain what's going on here?
As a sidenote, I am currently solving this using the description() method.
This is by design - it is how Swift's Dictionary is implemented:
Swift’s Dictionary type implements its key-value subscripting as a subscript that takes and returns an optional type. [...] The Dictionary type uses an optional subscript type to model the fact that not every key will have a value, and to give a way to delete a value for a key by assigning a nil value for that key. (link to documentation)
You can unwrap the result in an if let construct to get rid of optional, like this:
if let val = dictionary["anotherKey"] {
... // Here, val is not optional
}
If you are certain that the value is there, for example, because you put it into the dictionary a few steps before, you could force unwrapping with the ! operator as well:
let key: String = String(dictionary["anotherKey"]!)
You are misunderstanding the result. The String initializer does not return an optional. It returns the string representation of an optional. It is an non-optional String with value "Optional(42)".
A Swift dictionary always return an Optional.
dictionary["anotherKey"] gives Optional(42), so String(dictionary["anotherKey"]) gives "Optional(42)" exactly as expected (because the Optional type conforms to StringLiteralConvertible, so you get a String representation of the Optional).
You have to unwrap, with if let for example.
if let key = dictionary["anotherKey"] {
// use `key` here
}
This is when the compiler already knows the type of the dictionary value.
If not, for example if the type is AnyObject, you can use as? String:
if let key = dictionary["anotherKey"] as? String {
// use `key` here
}
or as an Int if the AnyObject is actually an Int:
if let key = dictionary["anotherKey"] as? Int {
// use `key` here
}
or use Int() to convert the string number into an integer:
if let stringKey = dictionary["anotherKey"], intKey = Int(stringKey) {
// use `intKey` here
}
You can also avoid force unwrapping by using default for the case that there is no such key in dictionary
var dictionary = ["anotherkey" : 42]
let key: String =
String(dictionary["anotherkey", default: 0])
print(key)

Cannot convert value of type 'String!' to expected argument type error

I have a public function:
public func lastActivityFor(userName: String) -> String { ... }
and later I want to call it as:
OneLastActivity.lastActivityFor("username")
but the last line get error:
Cannot convert value of type 'String!' to expected argument type 'OneLastActivity'
Why it appears if I send to those function String as suggested?(userName: String)
Any ideas how can I fix it? If you want more code, just ask me about.
Just create an instance of your class this way:
let temp = OneLastActivity()
Now you can use it's method:
temp.lastActivityFor("username")
Or you can directly use it this way:
OneLastActivity().lastActivityFor("username")
Hope it helps.

Convert AnyObject to an Int

I'm trying to convert a anyObject to an Int. Here's my code:
println(currentObject[0])
println(_stdlib_getDemangledTypeName(currentObject[0]))
2
Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>
I'm trying to convert currentObject[0] to an Int. Here's what I tried:
let num: Int = currentObjec[0] as! Int
When I run the app, I get the following error:
Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88)
When I try this: currentObject[0].toInt()
I get an error saying
'AnyObject' does not have a member named 'toInt()'
The only way I'm able to make it work, is to do the following:
let numStr = currentObject[0] as! String
let num: Int = numStr.toInt()!
Is there a simpler way to do it? (Without having to first convert it to a String.)
From the error message
Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88)
you can conclude that currentObject[0] is actually an NSString.
In that case you can simply convert it with
let numStr = currentObject[0].integerValue
But note that this will crash if the array element is not an NSString.

Resources