How to convert AnyObject type to Int in Swift

后端 未结 3 639
野性不改
野性不改 2021-02-06 03:47

I am searching a key in an Array of Dictionarys and I want to convert the result value into an Int value. This is what I tried.

         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 04:33

    If your data is decoded from JSON string, it will be decoded as NSNumber or NSString.

    You can use this function:

    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)
        }
    }
    

提交回复
热议问题