【发布时间】:2016-07-20 17:51:19
【问题描述】:
我对 iOS 编码还比较陌生,还没有完全理解选项、向下转换、字典和相关有趣的概念。我将非常感谢以下方面的帮助。
我正在从数据库下载数据并希望对数据进行检查以避免崩溃。在这种特殊情况下,我想在执行任务之前检查字典中的 Object 是否是 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)
}
我遵循了这个相关question and answer 的方法。但是,问题在于“if (jsonDictionary["SUNDAY OPEN TIME"] as?[Int]) != nil”这一行永远不会成立。我相信这是因为该值是一个可选对象。我尝试将字典调整为 [String:AnyObject] 类型,但这没有影响。
我被困住了,您的任何想法都将不胜感激。如果有更多有用的细节,请告诉我。谢谢!
【问题讨论】:
-
jsonDictionary["SUNDAY OPEN TIME"]的值是多少? -
应该是
Int还是[Int]?它们不是一回事,如果您的 if 语句为真,您的程序只会在下一行崩溃,因为该转换总是会失败。 -
尝试使用
jsonDictionary["SUNDAY OPEN TIME"] as? [Int]) is[NSNull()来检查是否为空。 -
它应该是一个 Int,而不是 [Int]。哇!
标签: ios swift dictionary