ios - How to convert Any to Int in swift? -
before asking question have searched stackoverflow's related questions, , found similar one: how convert int in swift.
my requirement not less:
let tresult = result as? [string:anyobject] let statecode = tresult?["result"] as? int
my need if tresult?["result"]
string
class, want convert int
too, rather nil
.
in objective-c
, wrote class method
converted int
:
+ (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 possible write similar class method
using swift3?
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
Comments
Post a Comment