简体   繁体   中英

Determine “nil” value in JSON

The app receives JSON object from the server. And some field in the object can be missing, or be nil . So, I need to find them before computing a value. I have a code fragment as below:

print(package["store"]!["cover"]) //here, console output: "nil"
if ((package["store"]!["cover"]) != nil) {
    //the 'if' statment above has no effect, statment below is executed,
    // and error occurs.
    imageName = STATIC_IMAGE_URL + (package["cover"] as! String)
}

How can I detect if the response JSON has some missing or nil fields?

You can use optional chaining , optional binding , and conditional casting combined in the same if-let statement:

if let cover = package["store"]?["cover"] as? String {
    imageName = STATIC_IMAGE_URL + cover
} else {
    imageName = "someDefaultImage"
}

It works like this:

  • package["store"]?["cover"] will return nil if either package["store"] , or package["store"]["cover"] is nil
  • the conditional cast as? String as? String returns nil if the expression to the left is not a String
  • finally the if-let construct will either populate cover with the actual string, or will go on the else branch if there's no match

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM