如何在Swift中将Any转换为Int?

时间:2016-11-10 08:28:17

标签: ios swift string

在提出这个问题之前,我已经搜索了Stackoverflow的相关问题,并找到了类似的问题:How to convert Any to Int in Swift

我的要求不是那么少:

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

我的需求是tResult?["result"]String类,我希望它也转换为Int,而不是nil

objective-c,我写了一个class method来获得转换后的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;
}

是否可以使用Swift3编写类似的class method

4 个答案:

答案 0 :(得分:5)

不那么详细的回答:

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

答案 1 :(得分:3)

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

您不需要任何自己的class methods

答案 2 :(得分:2)

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
}

这样的事情应该有效

答案 3 :(得分:2)

试试这个

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
}