我有一些JSON数据我正在使用swiftyJSON。我把它放入核心数据中。如果所有字段都在那里,它工作正常,但有些字段是空的,我试图"保护"反对空洞的。
如果所有字段都已填充,那么这部分代码可以正常工作:
// Iterate through each item in the JSON
for (_,subJson) in readableJSON[]["data"] {
let title = subJson["title"].string!
let url_title = subJson["url_title"].string!
let entry_id = subJson["entry_id"].string!
let newPet: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Pets", inManagedObjectContext: context)
// Store the data in CoreData "Pets"
newPet.setValue(self.title, forKey: "title")
newPet.setValue(url_title, forKey: "url_title")
newPet.setValue(entry_id, forKey: "entry_id")
} // end of "for items in JSON struck
但是,为了尝试防范空字段,我尝试将其用于JSON迭代:
if let entry_id = subJson["entry_id"].string {}
但是当我这样做时,newPet.setValue
会抛出这个错误:
使用未解析的标识符' entry_id'
在这种情况下,我知道entry_id始终存在,所以我很困惑。
思想?
答案 0 :(得分:1)
if let
语句仅在其自己的块中绑定该变量:
if let entry_id = subJson["entry_id"].string {
//entry_id exists in this block, and is non-nil
}
else {
//entry_id was nil, doesn't exist
}
//entry_id doesn't exist anymore
如果要为父作用域绑定该名称,请使用guard let
:
guard let entry_id = subJson["entry_id"].string else {
//entry_id was nil, doesn't exist
//you MUST break, return, or call a @noreturn function from here
}
//entry_id exists for the rest of this scope, and is non-nil