简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM