我在一个Dictionarys数组中搜索一个键,我想将结果值转换为Int值.这就是我试过的.
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 =结果为? NSNumber无法按预期工作.转换此值的正确方法是什么?
解决方法
我不知道您的代码,但这对您有所帮助.
您可以通过这种方式获取AnyObject值…
let data :AnyObject = "100" let score = Int(data as! String)! //Force Unwrap optional value it will be dengerIoUs for nil condition. print(score)
或者也尝试这种方式
let hitCount = "100" let data :AnyObject = hitCount as AnyObject //sometime Xcode will ask value type let score = Int(data as? String ?? "") ?? 0 print(score)
输出 –
Swift 3.1&斯威夫特4
let hitCount = "100" let data :Any = hitCount //Any type Value passing here let score = Int(data as? String ?? "") ?? 0 print(score)
输出 –