guard let / if let

guard let的意思与if let都是针对于可选类型进行解包,使用guard let可以是代码更加清晰易读

let dictionary: Dictionary? = ["data": ["book" : ["id" : "1"]]]
if let dict = dictionary {
    if let data = dict["data"] as? Dictionary {
        if let book = data["book"] as? Dictionary {
            if let id = book["id"] as? String {
                print(id)
            }
        }
    }
}

使用guard let与if的条件是一样的,只是需要加上else return,这样使用便不会嵌套很多if层,看起来更加直观。

let dictionary: Dictionary? = ["data": ["book" : ["id" : "1"]]]
guard let dict = dictionary else { return }
guard let data = dict["data"] as? Dictionary else { return }
guard let book = data["book"] as? Dictionary else { return }
guard let id = book["id"] as?String else { return }
print(id)

你可能感兴趣的:(guard let / if let)