[英]How to convert AnyObject type to Int in Swift
I am searching a key in an Array
of Dictionarys
and I want to convert the result value into an Int
value. 我在一个
Dictionarys
Array
中搜索一个键,我想将结果值转换为Int
值。 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
但是
if let number = result as? NSNumber
if let number = result as? NSNumber
doesn't work as expected. if let number = result as? NSNumber
无法按预期工作。 What is the correct way to convert this value? 转换此值的正确方法是什么?
I don't know your code but this will be helpful for you. 我不知道你的代码,但这对你有帮助。
You can get your AnyObject value in this way... 您可以通过这种方式获取AnyObject值...
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)
let hitCount = "100"
let data :Any = hitCount //Any type Value passing here
let score = Int(data as? String ?? "") ?? 0
print(score)
If your data is decoded from JSON string, it will be decoded as NSNumber or NSString. 如果您的数据是从JSON字符串解码的,它将被解码为NSNumber或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)
}
}
Here i have given example to convert Anyobject to Int and String 这里我给出了将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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.