Swift if let & guard let 语法糖

if letguard let 语法糖

//如果没有if let
func doSomethings(str:String?){
    let okStr = str
    if okStr != nil{
        //use okStr do something!
    }
}
//if let
func doSomethings(str:String?){
    if let okStr = str {
        //use okStr do something!
    }
}
//如果没有guard let
func doSomethings(str:String?){
    let okStr = str
    if okStr == nil{
        return
    }
    //use okStr do something!
}
//guard let
func doSomethings(str:String?){
    guard let okStr = str else{
        //okStr no exist!
        return
    }
    //use okStr do Something
}

总结:

if let okStr = str {...}如果 str 存在,则...(干点事情)

guard:"警卫,保卫" 多用来处理提前返回,防止代码嵌套过多。
guard let okStr = str else {...}
如果 str 存在则继续执行,不存在则...(干点事情)

你可能感兴趣的:(Swift if let & guard let 语法糖)