cannot convert a dictionary's int-value to String in swift - swift

I have a webService, which is returning some data. here is the link http://portal.pfs-ltd.org/LoginService1114?deviceid=89A04BDB-53AA-4441-9AFD-287729ACFE7F&imeino=12345678&SerialNo=f7pln20mfpfl&username=TST0002&password=TST0002&type=agent&status=Login&flag=True&Brand=Ipad&SimSerialNumber=&TelePhoneNumber=&Model=0&InstalledVersion=1.0
I'm unable to convert the value(int) for a key to a var of type String
var ApplicationVersion: String = dict["ApplicationVersion"] as String

as is for typecasting, not converting. You need to make a string from the integer value:
let version = dict["ApplicationVersion"] as Int
let applicationVersion = "\(version)"
Note that this performs no safety checking or validation.

Your json is not a dictionary, but a nested array.
let json: [AnyObject] = ...
let dict = json[0][0] as NSDictionary
var applicationVersion = String(dict["ApplicationVersion"] as Int)

Related

How to retrieve an int-type data from firebase to xcode? (Error: Cannot convert value of type 'String' to expected argument type 'Int')

I was trying to fetch data from firebase to my xcode project. The only fields I have are 'userName', 'age', and 'number'. I was trying to append the values into arrays userNames, ages, and numbers. However, I get the error Error: Cannot convert value of type 'String' to expected argument type 'Int in the appending age and number lines. They both have been entered as Int types in the database.
I thought about converting the values of the database into Int types since I think Xcode is taking them as String types? I tried, but I think my code itself was wrong so I couldn't solve it. I would appreciate the help!
func fetchData () {
let database = Firestore.firestore()
database.collection("users").addSnapshotListener {(snap, Error) in
if Error != nil {
print("Error")
return
}
for i in snap!.documentChanges {
let documentID = i.document.documentID
let userName = i.document.get("userName")
let age = i.document.get("age")
let number = i.document.get("number")
DispatchQueue.main.async {
self.userNames.append("\(userName)")
self.ages.append("\(Int(age))") // error line
self.numbers.append("Int\(number)") // error line
}
}
}
}
You can try to coerce the data into the types you want by using as?. (get returns Any? by default)
let userName = i.document.get("userName") as? String
let age = i.document.get("age") as? Int
let number = i.document.get("number") as? Int
Keep in mind that you'll end up with Optional values, so you'll need to have a fallback in case you don't get the type you expect.
If you wanted to provide defaults, you could do:
let userName = i.document.get("userName") as? String ?? ""
let age = i.document.get("age") as? Int ?? 0
let number = i.document.get("number") as? Int ?? 0
Then, later:
self.userNames.append(userName)
self.ages.append(age)
Note that your compilation errors were happening because you were trying to store String values ("") in an [Int]
In general, rather than storing all of these in separate arrays, you may want to look into making a struct to represent your data and storing a single array with that type. See this answer for an example: https://stackoverflow.com/a/67712824/560942
And, the Firestore documentation on custom objects: https://firebase.google.com/docs/firestore/manage-data/add-data#custom_objects

Cannot convert value of type '[String]?' to expected argument type 'String' Swift

I got lat long from API in string format now i want to change it to double.
let latitudeAll = [String]()
let double =
NSNumberFormatter().numberFromString(latitudeAll)?.doubleValue
You need to access the particular array object with its index.
if latitudeAll.count > 0 {
let double = NSNumberFormatter().numberFromString(latitudeAll[0])?.doubleValue
}
if you want Double Array from String array use this.
var doubleArr = latitudeAll.map { Double($0) }
Here doubleArr is type of [Double?]

swift compilation error: Downcast from 'String?!' to 'String' only unwraps optionals; did you mean to use '!!'?

After upgrading to cocoapods 1.0, I get this compilation error for these lines of code:
var strName = String()
var strEmail = String()
var strFacebookID = String()
var strPassword = String()
var objHelper = Helper()
....
let strFirstName = result["first_name"] as! String
let strLastName = result["last_name"] as! String
self.strName = strFirstName + "_" + strLastName
self.strEmail = result["email"] as! String
self.strFacebookID = result["id"] as! String
Downcast from 'String?!' to 'String' only unwraps optionals; did you mean to use '!!'?
Here is a screenshot of the error in detail:
http://imgur.com/Efe1nQf
UPDATE:
more code here: https://gist.github.com/anonymous/9c91c2eb1ccf269e78a118970468d1e8
The error message says that result itself is an optional so you have to unwrap both result and the value respectively.
let strFirstName = result!["first_name"] as! String
or better using optional binding for more safety and less type casting
if let userData = result as? [String:String] {
let strFirstName = userData["first_name"]!
let strLastName = userData["last_name"]!
}
result["key"] itself returns an optional, because there is a possibility that the key doesn't exist in the dictionary.
You'd need to first unwrap that optional, and then cast the returned value to a String. Try this:
let strFirstName = result["first_name"]! as! String
This is kind of a code smell, it's a lot of casting. Perhaps that dictionary should be of type [String : String] rather than what it is now.
For me just removing the as! String worked.
So instead of,
let strFirstName = result!["first_name"] as! String
replace with,
let strFirstName = result!["first_name"]

How to convert string in JSON to int Swift

self.event?["start"].string
The output is = Optional("1423269000000")
I want to get 1423269000000 as an Int
How can we achieve this? I have tried many ways such NSString (but it changed the value)
Your value: 1,423,269,000,000 is bigger than max Int32 value: 2,147,483,647. This may cause unexpected casting value. For more information, check this out: Numeric Types.
Try to run this code:
let maxIntegerValue = Int.max
println("Max integer value is: \(maxIntegerValue)")
In iPhone 4S simulator, the console output is:
Max integer value is: 2147483647
And iPhone 6 simulator, the console output is:
Max integer value is: 9223372036854775807
This information may help you.
But normally to convert Int to String:
let mInt : Int = 123
var mString = String(mInt)
And convert String to Int:
let mString : String = "123"
let mInt : Int? = mString.toInt()
if (mInt != null) {
// converted String to Int
}
Here is my safe way to do this using Optional Binding:
var json : [String:String];
json = ["key":"123"];
if var integerJson = json["key"]!.toInt(){
println("Integer conversion successful : \(integerJson)")
}
else{
println("Integer conversion failed")
}
Output:
Integer conversion successful :123
So this way one can be sure if the conversion was successful or not, using Optional Binding
I'm not sure about your question, but say you have a dictionary (Where it was JSON or not) You can do this:
var dict: [String : String]
dict = ["key1" : "123"]
var x : Int
x = dict["key1"].toInt()
println(x)
Just in case someone's still looking for an updated answer, here's the Swift 5+ version:
let jsonDict = ["key": "123"];
// Validation
guard let value = Int(jsonDict["key"]) else {
print("Error! Unexpected value.")
return
}
print("Integer conversion successful: \(value)")
// Prints "Integer conversion successful: 123"

How to convert Any to Int in Swift

I get an error when declaring i
var users = Array<Dictionary<String,Any>>()
users.append(["Name":"user1","Age":20])
var i:Int = Int(users[0]["Age"])
How to get the int value?
var i = users[0]["Age"] as Int
As GoZoner points out, if you don't know that the downcast will succeed, use:
var i = users[0]["Age"] as? Int
The result will be nil if it fails
Swift 4 answer :
if let str = users[0]["Age"] as? String, let i = Int(str) {
// do what you want with i
}
If you are sure the result is an Int then use:
var i = users[0]["Age"] as! Int
but if you are unsure and want a nil value if it is not an Int then use:
var i = users[0]["Age"] as? Int
“Use the optional form of the type cast operator (as?) when you are
not sure if the downcast will succeed. This form of the operator will
always return an optional value, and the value will be nil if the
downcast was not possible. This enables you to check for a successful
downcast.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itun.es/us/jEUH0.l
This may have worked previously, but it's not the answer for Swift 3. Just to clarify, I don't have the answer for Swift 3, below is my testing using the above answer, and clearly it doesn't work.
My data comes from an NSDictionary
print("subvalue[multi] = \(subvalue["multi"]!)")
print("as Int = \(subvalue["multi"]! as? Int)")
if let multiString = subvalue["multi"] as? String {
print("as String = \(multiString)")
print("as Int = \(Int(multiString)!)")
}
The output generated is:
subvalue[multi] = 1
as Int = nil
Just to spell it out:
a) The original value is of type Any? and the value is: 1
b) Casting to Int results in nil
c) Casting to String results in nil (the print lines never execute)
EDIT
The answer is to use NSNumber
let num = subvalue["multi"] as? NSNumber
Then we can convert the number to an integer
let myint = num.intValue
if let id = json["productID"] as? String {
self.productID = Int32(id, radix: 10)!
}
This worked for me. json["productID"] is of type Any.
If it can be cast to a string, then convert it to an Integer.