Guard检查条件,如果条件为假,则进入分支。后卫检查分支必须离开其封闭块或者通过return,break或continue(如果适用); 否则会导致编译器错误。这样做的好处是,在guard写入a时,不可能让流程意外继续(如可能if)。
使用防护可以帮助将嵌套级别保持在较低水平,这通常可以提高代码的可读性。
func printNum(num: Int) { guard num == 10 else { print("num is not 10") return } print("num is 10") }
Guard还可以检查可选值中是否有值,然后在外部范围中将其取消包装:
func printOptionalNum(num: Int?) { guard let unwrappedNum = num else { print("num does not exist") return } print(unwrappedNum) }
Guard可以使用where关键字将可选的展开和条件检查结合使用:
func printOptionalNum(num: Int?) { guard let unwrappedNum = num, unwrappedNum == 10 else { print("num does not exist or is not 10") return } print(unwrappedNum) }