[英]Check if an Object in a Dictionary is an Int (Swift)
我对编写iOS编程还比较陌生,还没有完全了解可选参数,向下转换,字典和相关的有趣概念。 在以下方面,我将不胜感激。
我正在从数据库下载数据,并希望对数据进行检查以避免崩溃。 在这种特殊情况下,我想在执行任务以避免崩溃之前检查字典中的对象是否为Int。
//The downloaded dictionary includes Int, Double and String data
var dictionaryDownloaded:[NSDictionary] = [NSDictionary]()
//Other code for downloading the data into the dictionary not shown.
for index in 1...dictionaryDownloaded.count {
let jsonDictionary:NSDictionary = self.dictionaryDownloaded[index]
if (jsonDictionary["SUNDAY OPEN TIME"] as? [Int]) != nil {
self.currentlyConstructingRecommendation.sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as! Int!
}
self.recommendationsArray.append(currentlyConstructingRecommendation)
}
我遵循了相关问答中的方法。 但是,问题是“如果(jsonDictionary [“ SUNDAY OPEN TIME”] as?[Int])!= nil”这一行从不成立。 我相信这是因为该值是一个可选对象。 我尝试将字典调整为[String:AnyObject]类型,但这没有影响。
我被困住了,您的任何想法都将不胜感激。 请让我知道是否有更多有用的细节。 谢谢!
使用以下代码: jsonDictionary["SUNDAY OPEN TIME"] as? [Int]
jsonDictionary["SUNDAY OPEN TIME"] as? [Int]
,您正在尝试将值转换为Array<Int>
,而不是Int
。
并且在代码中,您还有另一个缺陷: index in 1...dictionaryDownloaded.count
。 当index
到达dictionaryDownloaded.count
时,这将导致索引超出范围异常。
因此,一个快速的解决方法是:
for index in 0..<dictionaryDownloaded.count {
let jsonDictionary:NSDictionary = self.dictionaryDownloaded[index]
if (jsonDictionary["SUNDAY OPEN TIME"] as? Int) != nil {
self.currentlyConstructingRecommendation.sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as! Int!
}
self.recommendationsArray.append(currentlyConstructingRecommendation)
}
但我建议您以一种更加快捷的方式进行操作。
for jsonDictionary in dictionaryDownloaded {
if let sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as? Int {
self.currentlyConstructingRecommendation.sundayOpenTime = sundayOpenTime
}
self.recommendationsArray.append(currentlyConstructingRecommendation)
}
我认为您已经将Int
(这是一个整数)与[Int]
(这是一个整数s的数组 )混淆了。 此外,这段代码是多余的:
if (jsonDictionary["SUNDAY OPEN TIME"] as? [Int]) != nil {
self.currentlyConstructingRecommendation.sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as! Int!
}
您用的出色as?
操作符执行条件转换,但随后您将结果丢弃,并将危险as!
在下一行。 您可以使用if let
更安全,更清晰:
if let sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME] as? Int {
self.currentlyConstructingRecommendation.sundayOpenTime = sundayOpenTime
}
这将类型强制转换为Int
,如果结果不是nil
,则将其解包并sundayOpenTime
设置sundayOpenTime
。 然后,在下一行中使用Int
类型的这个新的sundayOpenTime
常量。 但是,如果强制转换的结果为 nil
,则整个if
语句将失败,我们将继续进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.