guard let的意思与if let都是针对于可选类型进行解包,使用guard let可以是代码更加清晰易读
let dictionary: Dictionary<String, Any>? = ["data": ["book" : ["id" : "1"]]]
if let dict = dictionary {
if let data = dict["data"] as? Dictionary<String, Any> {
if let book = data["book"] as? Dictionary<String, Any> {
if let id = book["id"] as? String {
print(id)
}
}
}
}
使用guard let与if的条件是一样的,只是需要加上else return,这样使用便不会嵌套很多if层,看起来更加直观。
let dictionary: Dictionary<String, Any>? = ["data": ["book" : ["id" : "1"]]]
guard let dict = dictionary else { return }
guard let data = dict["data"] as? Dictionary<String, Any> else { return }
guard let book = data["book"] as? Dictionary<String, Any> else { return }
guard let id = book["id"] as?String else { return }
print(id)