9

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.

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

But if let number = result as? NSNumber doesn't work as expected. What is the correct way to convert this value?

return true
  • 7,839
  • 2
  • 19
  • 35
Irrd
  • 325
  • 1
  • 6
  • 18

3 Answers3

18

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 -

result


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 -

enter image description here

Community
  • 1
  • 1
Anand Nimje
  • 6,163
  • 4
  • 24
  • 43
  • 1
    So whats the best way for get optional value to non optional. Tell me @dfri ?? – Anand Nimje Jul 14 '16 at 11:49
  • 2
    Read [this excellent canonical answer](http://stackoverflow.com/a/32170457/4573247) on the subject. Quote: _"As a general rule, **you should never explicitly force unwrap an optional** with the ! operator"_. – dfrib Jul 14 '16 at 11:59
  • 1
    @dfri In your `Or try this way also`: if the `data:Anyobject`'s value is "abc",could use your method? – aircraft Nov 10 '16 at 08:27
  • @aircraft I'm sorry, I don't follow. What do you mean by "in _your_ `Or try this way also`"? Note that the thread I linked to is a (great) canonical answer on optionals in general, but I'm not the one who has written it. – dfrib Nov 10 '16 at 10:43
  • It takes a lot of conversions to get what is asked. Why is that Swift!!.. – Dearwolves Feb 20 '17 at 09:23
1

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)
    }
}
Hao
  • 201
  • 1
  • 3
0

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)
        }
    }
Bhoomi Jagani
  • 2,413
  • 18
  • 24