如何在Swift

时间:2016-07-14 08:46:59

标签: ios swift int

我正在Array Dictionarys中搜索密钥,我希望将结果值转换为Int值。这就是我的尝试。

if let result = lasrIDArray.flatMap( {$0["\(self.selectedTitle)"]} ).first {      
    print(result)

    if let number = result as? NSNumber {
        let tag = number.integerValue
        let currentScroll = view.viewWithTag(Int(api.selectedCatID)!) as! UIScrollView
        let lastImgVw = currentScroll.viewWithTag(tag) as! UIImageView
        print(lastImgVw.frame.origin.y)
    }
}

但是if let number = result as? NSNumber并没有按预期工作。转换此值的正确方法是什么?

3 个答案:

答案 0 :(得分:15)

我不知道您的代码,但这会对您有所帮助。

您可以通过这种方式获取 AnyObject 值...

let data :AnyObject = "100"
let score = Int(data as! String)! //Force Unwrap optional value it will be dengerious for nil condition.
print(score)

或者尝试这种方式

let hitCount = "100"
let data :AnyObject = hitCount as AnyObject //sometime Xcode will ask value type
let score = Int(data as? String ?? "") ?? 0
print(score)

输出 -

result

Swift 3.1&斯威夫特4

let hitCount = "100"
let data :Any = hitCount //Any type Value passing here 
let score = Int(data as? String ?? "") ?? 0
print(score)

输出 -

enter image description here

答案 1 :(得分:1)

如果您的数据是从JSON字符串解码的,它将被解码为NSNumber或NSString。

您可以使用此功能:

func intValueForKey(key: String, inDictionary dictionary: [String: AnyObject]) throws -> Int {
    if let value = dictionary[key]?.integerValue {
        return value
    } else {
        throw NSError(domain: "Invalid key", code: -1, userInfo: nil)
    }
}

答案 2 :(得分:0)

这里我给出了将Anyobject转换为Int和String

的示例
var idInt : Int = 0
if let ids: AnyObject = responseDict["id"] {
    if let idsInt = ids as? Int{
        idInt  = idsInt
        print(idInt)
    }
}


var nameString : String = ""
    if let name: AnyObject = responseDict["name"] {
        if let nameStr = name as? String{
            nameString  = nameStr
            print(nameString)
        }
    }