guard 的使用
1.guard 是 Swift2.0新增的语法
2.它与 if语句非常类似,它设计的目的是提高程序的可读性
3.guard 语句必须带有 else语句,它的语法如下:
3.1.当条件表达式为 true的时候跳过 else 语句中的内容,执行语句组内容
3.2.条件表达式为 false的时候执行 else语句中的内容,跳转语句一般是 return,break,continue和 throw
guard 用法举例
以下举例说明其中的区别:
需求:判断一个用户名是否是联通号,开发中用户名验证的过程,分以下几步:
1,用户名不能为 null;
2,用户名必须是手机号码
3,用户名是 186开头的手机号
if ... else 示例
//: Playground - noun: a place where people can play
import UIKit
func isUserName(username : String){
if username != nil {
if isPhoneNumber(username: username) {
if isUnicom(username: username){
print("手机号是联通号码!")
}else{
print("手机号不是联通号码!")
}
}else{
print("用户名不是手机号!")
}
}else{
print("用户名为空!")
}
}
func isPhoneNumber (username : String) -> Bool{
//判断是否是手机号码,代码略
return true
}
func isUnicom(username :String) -> Bool{
//判断是否是联通号码,代码略
return true
}
isUserName(username : "18600000000")
guard 用法示例
//guard 用法比较条理,代码可读性较强
func isUserNameGuard( username : String) -> Void{
guard username != nil else {
print("用户名为空!")
return
}
guard isPhoneNumber(username : username) else {
print("用户名不是手机号!")
return
}
guard isUnicom(username: username) else {
print("手机号不是联通号码!")
return
}
print("手机号是联通号码!")
}
func isPhoneNumber (username : String) -> Bool{
//判断是否是手机号码,代码略
return true
}
func isUnicom(username :String) -> Bool{
//判断是否是联通号码,代码略
return true
}
isUserNameGuard(username: "18600000000")
通过对比,可以看出,使用 guard 可以增进代码的阅读性。