aircraft aircraft -4 years ago 264
Swift Question

How to convert Any to Int in swift?

Before asking this question I have searched the Stackoverflow's related questions, and found a similar one: How to convert Any to Int in Swift.

My requirement is not that less:

let tResult = result as? [String:AnyObject]
let stateCode = tResult?["result"] as? Int

My need is if the
is a
class, I want it to be convert to
too, rather than to

, I wrote a
class method
to get the converted

+ (NSInteger)getIntegerFromIdValue:(id)value
NSString *strValue;
NSInteger ret = 0;
if(value != nil){
strValue = [NSString stringWithFormat:@"%@", value];
if(![strValue isEqualToString:@""] && ![strValue isEqualToString:@"null"]){
ret = [strValue intValue];
return ret;

Is it possible to write a similar
class method
using Swift3?

Answer Source

Less verbose answer:

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


let tResult: [String: Any]? = ["result": 123] // stateCode: 123
let tResult: [String: Any]? = ["result": "123"] // stateCode: 123
let tResult: [String: Any]? = ["result": "abc"] // stateCode: nil
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download