Swift Guard Statement

When the first saw the Swift guard statement during Apple’s Platform State of the Union, I couldn’t quite understand why I would ever use it. So what is it?

Like an if statement, guard executes statements based on a Boolean value of an expression. Unlike an if statement, guard statements only run if the conditions are not met. You can think of guard more like an Assert, but rather than crashing, you can gracefully exit.

Even after seeing some examples, I only saw it as a confusing way to accomplish what we already could with Optional Binding or with if-else statements alone.

Diving In

Let’s take a simple example comparing current techniques vs using the new guard statement:

1 func fooManualCheck(x: Int?) {
2     if x == nil || x <= 0 {
3         // Value requirements not met, do something
4         return
5     }
6
7     // Do stuff with x
8     x!.description
9 }

This is the most basic Objective-C style way to make sure a value exists and that it meets a condition. Now this works fine, but has a couple flaws:

  1. You’re checking for a condition that you don’t want, rather than checking for the value you do want. Code becomes confusing when you have a bunch of checks like this. What you’re hoping for here is that your condition actually doesn’t pass.
  2. You also need to force unwrap the optional value after the condition fails.

Swift gave us a way to clean this up and fix some of these flaws through Optional Binding:

1 func fooBinding(x: Int?) {
2     if let x = x where x > 0 {
3         // Do stuff with x
4         x.description
5     }
6
7     // Value requirements not met, do something
8 }

This removes both of the flaws that the first function had, but adds a new one. Here you’re putting your desired code within all the conditions, rather than afterward. You might not immediately see a problem with this, but you could imagine how confusing it could become if it was nested with numerous conditions that all needed to be met before running your statements.

The way to clean this up is to do each of your checks first, and exit if any aren’t met. This allows easy understanding of what conditions will make this function exit.

I’ve heard this called the Bouncer Pattern, which makes a lot of sense. You want to get rid of the bad cases before they get in the door. It also allows you to think about one case at a time, rather than figuring out how all combinations need to work together.

Here enters the guard statement:

1 func fooGuard(x: Int?) {
2     guard let x = x where x > 0 else {
3         // Value requirements not met, do something
4         return
5     }
6
7     // Do stuff with x
8     x.description
9 }

Using guard solves all 3 of the issues mentioned above:

  1. Checking for the condition you do want, not the one you don’t. This again is similar to an assert. If the condition is not met, guard‘s else statement is run, which breaks out of the function.
  2. If the condition passes, the optional variable here is automatically unwrapped for you within the scope that the guard statement was called – in this case, the fooGuard(_:) function. This is an important, yet notably strange feature that really makes the guard statement useful.
  3. You are checking for bad cases early, making your function more readable and easier to maintain.

The cool thing is that this same pattern holds true for non-optional values as well:

 1 func fooNonOptionalGood(x: Int) {
 2     guard x > 0 else {
 3         // Value requirements not met, do something
 4         return
 5     }
 6
 7     // Do stuff with x
 8 }
 9
10 func fooNonOptionalBad(x: Int) {
11     if x <= 0 {
12         // Value requirements not met, do something
13         return
14     }
15
16     // Do stuff with x
17 }

Wrapping Up

This simple example shows how you could start using guard immediately in your Swift code to make your function/methods more clear. It’s easy for us to immediately judge the value of a new feature until you give it a chance and see what it can or can’t do for you.

Going from Objective-C to Swift is a huge change, not only to syntax, but how you have to look at architecting your code. You can only benefit from this awesome new language if you actively change your mindset while writing code by expanding your everyday patterns and style.

Reference:Swift Guard Statement

Reference:Swift的Guard语句

时间: 2024-10-02 07:54:41

Swift Guard Statement的相关文章

Swift - guard关键字(守护)

guard语句和if语句有点类似,都是根据其关键字之后的表达式的布尔值决定下一步执行什么.但与if语句不同的是,guard语句只会有一个代码块,不像if语句可以if else多个代码块. 那么guard语句的作用到底是什么呢?顾名思义,就是守护.guard语句判断其后的表达式布尔值为false时,才会执行之后代码块里的代码,如果为true,则跳过整个guard语句,我们举例来看看. 我们以今年高考为例,在进入考场时一般都会检查身份证和准考证,我们写这样一个方法: func checkup(per

Swift 2 有哪些新特性

在WWDC我们发现Swift团队没有浪费时间在无谓的地方,而是致力于改善Swift 2. 我们将会为你编写和录制很多关于Swift 2的教程,但在此期间我想强调Swift最令人兴奋的改变,为你可以在秋天迁移到Swift 2做准备. 错误处理 正如Ray在WWDC 2015 Initial Impressions文章中提及,错误处理已经在Swift 2改进了.我们已经迁移到新的系统就像异常处理,而不是NSError对象和双指针. 你可能对以下代码比较熟悉: Objective-C 1 2 3 4

Swift的Guard语句

转自:http://www.jianshu.com/p/3a8e45af7fdd 本篇文章翻译自:http://ericcerney.com/swift-guard-statement/原作者:ecerney原文章发布于2015-06-10*译者注:该语法为swift2.0新特性,目前(2015-07-30)仅xcode 7 beta支持,xcode6并不支持. 最开始在Apple的Platform State of the Union看见swift的guard语句的时候,我当时不太理解以后会有

swift2.0_语法改动详细说明

Swift2.0 语法改动详细说明 文档管理者:PMST 当前版本:V1.0.0 最后更新日期:2015.06.10(ps:swift2.0,开源之美) 注:[New]表示更新内容,此外有优秀文章.资源.框架等等,都可以推荐给我,发送到我的邮箱. 邮箱地址链接:[email protected] [6-08改动日志] 新增内容到Error Handling一节.Do Statement部分.Throw Statement部分.Defer Statement部分以及Try Operator部分.

Swift4.2语言参考(六) 声明

一个声明引入了一个新的名称或构建到你的程序.例如,您使用声明来引入函数和方法,引入变量和常量,以及定义枚举,结构,类和协议类型.您还可以使用声明来扩展现有命名类型的行为,并将符号导入到其他地方声明的程序中. 在Swift中,大多数声明也是定义,因为它们是在声明它们的同时实现或初始化的.也就是说,由于协议不实现其成员,因此大多数协议成员仅是声明.为方便起见,因为在Swift中区别并不重要,术语声明包括声明和定义. 1 GRAMMAR OF A DECLARATION 2 3 declaration

初识iOS9 iPad新特性SlideView和SplitView的适配

苹果刚发布了iOS9,在iPad上新增了两个新的特性SlideView和SplitView,前者可以在不关闭当前激活APP的情况下调出来另外个APP以30%比例显示进行操作使用,后者允许同时运行两个APP以50%50%,70%30%比例运行,感觉非常方便. 然而,方便了用户的同时却恶心了开发者,在同一屏幕运行两种APP的时候势必APP显示比例发生改变,那么就需要对几种不同的大小进行处理,好在苹果有Autolayout,并且在iOS8中新增了SizeClass特性,两者结合,可以很好的应付以上各种

Swift的if let和guard let的使用 &lt;一看就等哟&gt;

// // ViewController.swift // 可选项的判断 // // Created by 思 彭 on 16/9/16. // Copyright © 2016年 思 彭. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // demo1(x: 20, y: nil) de

swift中 if let 与 guard let 对比,guard会降低一个分支

1 //用if let与guard let实现同一效果,会发现guard降低一个分支 2 //可以用if var guard var 表示定义的变量能修改值 3 func test(){ 4 let name:String? = "张三" 5 6 if let a = name { 7 print(a) 8 }else{ 9 print("李四") 10 } 11 12 guard let c = name else { 13 print("李四"

Swift学习笔记-控制流(Control Flow)-提前退出(guard)

像if语句一样,guard的执行取决于一个表达式的布尔值.我们可以使用guard语句来要求条件必须为真时,以执行guard语句后的代码.不同于if语句,一个guard语句总是有一个else分句,如果条件不为真则执行else分局中的代码. func greet(person: [String: String]) { guard let name = person["name"] else { return } print("Hello \(name)") guard