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)