如何在Swift中将AnyObject类型转换为Int
问题描述:
我正在
Dictionarys
中搜索一个键,我想将结果值转换为 Int 值。这就是我试过的。
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)
}
}
但是如果让number = result为? NSNumber
无法按预期工作。转换此值的正确方法是什么?
But if let number = result as? NSNumber
doesn't work as expected. What is the correct way to convert this value?
答
我不知道您的代码,但这会有所帮助适合你。
您可以通过这种方式获得 AnyObject 值...
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 -
let hitCount = "100"
let data :Any = hitCount //Any type Value passing here
let score = Int(data as? String ?? "") ?? 0
print(score)
输出 -