Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Any to Int in swift?

Tags:

string

ios

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 tResult?["result"] is a String class, I want it to be convert to Int too, rather than to nil.

In objective-c, I wrote a class method to get the 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 it possible to write a similar class method using Swift3?

like image 548
aircraft Avatar asked Nov 10 '16 08:11

aircraft


4 Answers

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
like image 102
Andrey Gordeev Avatar answered Nov 20 '22 18:11

Andrey Gordeev


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

like image 36
Juan Carlos Ospina Gonzalez Avatar answered Nov 20 '22 18:11

Juan Carlos Ospina Gonzalez


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.

like image 3
user28434'mstep Avatar answered Nov 20 '22 19:11

user28434'mstep


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
}
like image 2
Prashant Tukadiya Avatar answered Nov 20 '22 19:11

Prashant Tukadiya