swift 闭包 可选项
This article was originally published on my website.
本文最初发布在我的网站上 。
In this tutorial, we’ll learn how to deal with Optionals in Swift.
在本教程中,我们将学习如何在Swift中处理Optionals。
什么是可选的? (What are optionals?)
Optionals are Swift Language traits that lets the programmer operate on a variable that may or may not have a value at a particular instance. Usually, this applies to async tasks such as Networking: When you make a request to a server for, say, a list of cat pictures the data in the variable will take some time to arrive. During this loading time if you’d try to access the value within this variable you will crash the application since the value is nil. Another example of this is when you’re trying to construct a URL from a string, you’d have noticed that the variable containing the URL becomes optional because the URL class may or may not be able to construct an URL from the given string. We’ll learn 4 different ways of dealing with optionals and a tip that I use during development.
可选的是Swift语言特性,可让程序员对在特定实例上可能具有或不具有值的变量进行操作。 通常,这适用于诸如网络之类的异步任务:当您向服务器请求猫列表时,变量中的数据将需要一些时间才能到达。 在此加载期间,如果您尝试访问此变量中的值,则该应用程序将崩溃,因为该值为nil。 另一个例子是,当您尝试从字符串构造URL时,您会注意到包含URL的变量变得可选,因为URL类可能会也可能无法从给定的字符串构造URL。 我们将学习4种处理可选选项的方法以及在开发过程中使用的技巧。
处理可选内容的各种方式 (Various ways of dealing with optionals)
Force Unwrapping (DO NOT USE THIS)
强制展开(请勿使用此功能)
nil coalescing
无合并
if let
如果让
guard let (Control Transfer)
守卫(控制权转移)
强制展开 (Force Unwrapping)
This is the most dangerous of all the techniques discussed in this tutorial. Force Unwrapping is the programmer taking responsibility and telling the compiler that they know for sure that some value will exist and in no way when they force unwrap that variable will they get nil. This is dangerous for several reasons. Let us take the URL construction example that we discussed above. If say, you’ve provided a string with htttps:// instead of https:// which can very well happen as a typo and you’ve written this code
这是本教程中讨论的所有技术中最危险的。 强制解包是程序员负责并告诉编译器,他们肯定知道某些值会存在,而当他们强制解包该变量时,绝不会得到零。 出于多种原因,这很危险。 让我们以上面讨论的URL构建示例为例。 如果说的话,您提供了一个带有htttps://而不是https://的字符串,这很可能会出现拼写错误,并且您已经编写了此代码
let url = URL(string: "htttps://google.com")! //Will Crash your application
This will crash your application as the URL object returned nil since it couldn’t construct a URL with the provided string. This is just the simplest of examples. Force Unwrapping becomes super dangerous in a big production application. When I was starting iOS development and learning the Swift Language I used to force unwrap all the time and then I’d notice Users complaining about the App randomly crashing on them. All because I used ! like way too much.
这将使您的应用程序崩溃,因为URL对象返回nil,因为它无法使用提供的字符串构造URL。 这只是最简单的示例。 在大型生产应用中,强制展开变得非常危险。 当我开始iOS开发并学习Swift语言时,我一直都在强迫解开包装,然后我发现用户抱怨App随机崩溃。 都是因为我用过! 太多了
无合并 (nil coalescing)
This is a sweet little way of dealing with optionals. Nil Colleasing is an operator called using ?? syntax. What this does is in case your value becomes nil it provides some default value that you define to your variable. This means that even if the value initially became nil it’ll still get a default value and therefore the value no longer remains optional. An example can be when you receive data from a JSON service you might have one optional key. You can provide a default value to the right of the nil coalescing operator to convert the optional into a non-optional
这是处理可选选项的好方法。 Nil Colleasing是使用??调用的运算符。 句法。 这是在您的值变为nil的情况下执行的操作,它提供了一些您为变量定义的默认值。 这意味着即使该值最初变为nil,它仍将获得默认值,因此该值不再是可选的。 例如,当您从JSON服务接收数据时,您可能具有一个可选键。 您可以在nil合并运算符的右侧提供一个默认值,以将可选值转换为非可选值
let catName = cats["name"].stringValue ?? "Sprinkles" //Get The Office reference? ;)
如果让 (if let)
if let is another technique to deal with optionals. Here the trick is simple, if a non-optional value could be created from an optional then it enters into the if block else it won’t. Let’s understand this with an example
如果let是另一种处理可选内容的技术。 这里的窍门很简单,如果可以从一个可选值中创建一个非可选值,那么它将进入if块,否则就不会。 让我们通过一个例子来理解这一点
if let catName = cats["name"].stringValue {
print("Successfully Unwrapped. The Cat name is \(catName)")
}
Here catName is a non-optional because only if the variable could be created as a non-optional does it enter into the if block. When accessing the value inside of the if block use the non-optional, in this case, catName
这里的catName是非可选的,因为只有将变量创建为非可选时,它才进入if块。 访问if块内部的值时,请使用非可选选项,在这种情况下,请使用catName
守卫 (guard let)
Finally, welcome to the world of guard let. Guard let is a control transfer syntax meaning it can transfer the control out of a particular scope. Guard let is useful when you want to escape from a function before it gets too late. guard let works a bit like if let but here if the non-optional value couldn’t be created then the control transfers out of the function. You have to put a return statement inside of the else block because guard statements cannot fall through. You have to either throw an error or return if you’re using the guard let statement.
最后,欢迎来到警卫队的世界。 Guard let是控件转移语法,这意味着它可以将控件转移到特定范围之外。 当您想在函数变得太晚之前退出函数时,Guard let很有用。 Guard let的工作方式类似于let,但是在这里,如果无法创建非可选值,则控件移出该函数。 您必须将return语句放入else块内部,因为后卫语句无法通过。 如果使用guard let语句,则必须抛出错误或返回错误。
guard let catName = cats["name"].stringValue else {
return //If catName couldn't be made, leave the function safely and early.
}
提示:断言 (Tip: Assert)
This is something that I learnt during my GSoC 2020 with VLC on their iOS project. When using a guard let statement I like to assert if there was an error i.e.: The optional couldn’t be unwrapped into a non-optional value. Assertions cause fatal errors in your code but the catch is that it only becomes a fatalError during DEBUG and not During production. This is excellent because it lets you point out the places your code is breaking forcing you to check the code since the application has crashed. An assertion failure looks something like this
这是我在使用VLC的GSoC 2020上的iOS项目中学到的。 当使用guard let语句时,我想断言是否存在错误,即:不能将可选选项解包为非可选值。 断言会在您的代码中导致致命错误,但要注意的是,它只会在DEBUG期间而不是生产期间变成致命错误。 这非常好,因为它可以指出由于应用程序崩溃而导致代码中断的地方,从而迫使您检查代码。 断言失败看起来像这样
guard let catName = cats["name"].stringValue else {
assertionFaliure("Couldn't unwrap Cat Name")
return
}
This helps so much during development that I can’t even tell you. You should use this.
这在开发过程中有很大帮助,我什至不告诉您。 您应该使用此。
That’s been it. Thank you for reading this and I hope you can now feel better about handling optionals. It’s, according to me, one of the best language traits second only to enums.
就是这样。 感谢您阅读本文,希望您现在可以更好地处理可选内容。 据我说,这是仅次于枚举的最好的语言特征之一。
翻译自: https://medium.com/@swapnanildhol/optionals-in-swift-25aef4eeab09
swift 闭包 可选项
本文深入探讨Swift中的可选值处理,包括强制展开、无合并、if let及guard let等技巧,旨在帮助开发者避免应用崩溃,提高代码健壮性。

1911

被折叠的 条评论
为什么被折叠?



