How to convert AnyObject type to Int in Swift

后端 未结 3 637
野性不改
野性不改 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:25

    Here i have given example to convert Anyobject to Int and 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)
            }
        }
    
    0 讨论(0)
  • 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)
        }
    }
    
    0 讨论(0)
  • 2021-02-06 04:38

    I don't know your code but this will be helpful for you.

    You can get your AnyObject value in this way...

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

    Or try this way also

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

    Output -


    Swift 3.1 & Swift 4

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

    Output -

    0 讨论(0)
提交回复
热议问题