How to convert Any to Int in Swift

if 
    let tResult = result as? [String:AnyObject],
    let stateCodeString = tResult["result"] as? String,
    let stateCode = Int(stateCodeString)
{
    // do something with your stateCode
}

And you don't need any own class methods.


Less verbose answer:

let key = "result"
let stateCode = tResult?[key] as? Int ?? Int(tResult?[key] as? String ?? "")

Results:

let tResult: [String: Any]? = ["result": 123] // stateCode: 123
let tResult: [String: Any]? = ["result": "123"] // stateCode: 123
let tResult: [String: Any]? = ["result": "abc"] // stateCode: nil

if let stateCode = tResult["result"] as? String {
    if let stateCodeInt = Int(stateCode){
        // stateCodeInt is Int
    }
}else if let stateCodeInt = tResult["result"] as? Int {
    // stateCodeInt is Int
}

Something like this should work


Try This

class func getIntegerFromIdValue(_ value: Any) -> Int {
    var strValue: String
    var ret = 0
    if value != nil {
        strValue = "\(value)"
        if !(strValue == "") && !(strValue == "null") {
            ret = Int((strValue as NSString ?? "0").intValue)
        }
    }
    return ret
}

Tags:

Swift