Swift - guard关键字(守护)

guard语句和if语句有点类似,都是根据其关键字之后的表达式的布尔值决定下一步执行什么。但与if语句不同的是,guard语句只会有一个代码块,不像if语句可以if else多个代码块。

1> guard 必须使用在函数里面
2> guard 语句必须带有else语句 语法如下: · 当条件表达式为 true时跳过 else语句内容,执行语句组内容 · 条件表达式为 false时执行 else内容, 跳过语句一般为 return、break、continue、throw.

以处理网络请求为例:

    //请求失败

    guard response.result.isSuccess else {

                fail(response.result.error)

                return

                

            }

            //请求成功

            if let jsonValue = response.result.value {

                let json = JSON(jsonValue)

                let dic = json.dictionaryObject

                success(dic!)

            }

当response.result.isSuccess为false时执行else里的语句,为true时执行下面请求成功语句。

猜你喜欢

转载自www.cnblogs.com/cui-cui/p/10102381.html
今日推荐