swift 闭包 可选项_Swift中的可选项

swift 闭包 可选项

You are probably aware of the stoptional. The urban dictionary defines it as “any stop sign located in a town with an incredibly small population in which no one is ever around.It is basically a stop sign where most people don’t stop. But if you get caught you would definitely get a ticket for it.

您可能知道惯用语 。 城市词典将其定义为“任何站点 标牌位于人口稀少的小镇,周围没人居住。 它基本上是一个停止的迹象,大多数人不停止。 但是,如果您被抓住,肯定会得到一张票。

Optionals in Swift are like that. They may or may not have a value depending on the situation. Remember when you programmed in C you had to check if a variable was null? If you did not check for null and if you tried to access the variable when it was indeed null, you would get a null pointer exception. Well, Optionals in Swift make the process of checking for null easier.

Swift中的可选选项就是这样。 根据情况,它们可能没有值。 还记得用C编程时必须检查变量是否为null吗? 如果您没有检查null并且在变量确实为null时尝试访问该变量,则将获得null pointer exception 。 好吧,Swift中的Optionals使检查null的过程更加容易。

这个怎么运作 (How it works)

Think of optionals like peanut shells . The kind you can find at Five Guys

想一想花生壳之类的可选配件。 你可以在五个家伙找到那种

When you open them, they usually contain peanuts. But every so often you find that the shell is empty. What do you do with the empty shells? You just throw them away. If you find a peanut or two inside the shell, you eat the peanuts. To know whether there is a peanut inside, you have to unwrap it by opening the shell. It is the same way with optionals. The optional variable actually may or may not contain a value. If it does not contain a value then it will equal nil and you cannot proceed with that variable. You throw it away. If it does contain a value, then you use it and proceed.

当您打开它们时,它们通常包含花生。 但是,每隔一段时间您就会发现外壳是空的。 空壳怎么办? 你只是把它们扔掉。 如果在壳内发现一两个花生,则可以吃花生。 要知道里面是否有花生,必须打开外壳将其拆开 。 与可选方法相同。 可选变量实际上可能包含也可能不包含值。 如果它不包含值,那么它将等于nil并且您无法继续使用该变量。 你扔掉它。 如果它确实包含一个值,则可以使用它并继续。

To tell the compiler and the programmer that a variable is an optional variable, you follow the variable name with a ?. There are usually only two situations in which the value of the variable will be nil.

要告诉编译器和程序员, 变量是可选变量 ,请在变量名后加上? 。 通常仅在两种情况下变量的值将为nil

  1. When the variable has been declared and not yet assigned a value, then it is nil

    当变量已声明且尚未分配值时,则为nil

  2. When at a later point in the variable’s life it is forcibly assigned a value of nil . Note that only optional variables can ever have a nil value.

    在变量寿命的后期,它会被强制赋值为nil 。 请注意,只有可选变量可以具有nil值。

它比旧的C语法更好 (How it is better than the old C syntax)

In the past you had to remember and explicitly check every time a variable could potentially have a null value. If it could possibly have a null value, you had to write code for that condition or catch the thrown error at a parent level. But with optionals in swift there are two ways you can circumvent this cumbersome process — if let and guard let

过去,您必须记住并明确检查每次变量可能具有空值的可能性。 如果它可能有一个空值,则必须为该条件编写代码或在父级别上捕获引发的错误。 但是,借助快速的可选选项,您可以通过两种方式来规避这一繁琐的过程- if letguard let

  1. With if let you can unwrap the optional. Now if the optional containted a value, the if block will be executed. If not the else block will be executed.

    使用if let可以解开可选项。 现在,如果可选包含值,则将执行if块。 如果不是,则将执行else块。

  2. With guard let also you can unwrap the optional. But if the optional does not contain a value, the process will exit the current scope and continue.

    有了guard let您还可以拆开选装件。 但是,如果可选参数不包含值,则该过程将退出当前范围并继续。

There is also a third way to unwrap an optional. By using an ! sign in the variable name in place of the ?. This is called forced unwrapping. You hope that the shell contains at least one peanut. At runtime, if you force unwrap an optional and it contains a value/peanut, then you can use/eat it. But if there is nothing in there (aka nil) then you end up having to eat peanut-shell which contains pesticides and fertilizers that are not good for digestion and you program will instantly crash. I don’t advise forced unwrapping — because that is like not checking for null. There are indeed some corner cases where you can force unwrap — but it is best to avoid them.

还有第三种方法来解开可选项。 通过使用! 在变量名上签名? 。 这称为强制展开。 您希望该壳至少包含一个花生。 在运行时,如果您强制解开一个可选值并且它包含一个值/花生,那么您可以使用/食用它。 但是,如果那里什么也没有(又称nil)那么您最终不得不吃花生壳,其中含有不利于消化的农药和肥料,您的程序将立即崩溃。 我不建议强制展开-因为这就像不检查null。 实际上,在某些极端情况下,您可以强制打开包装,但最好避免使用它们。

何时使用可选 (When to use Optionals)

You can use optionals to represent data that may be missing, unknown, or deleted. For example, let’s say you want to store the number of cherries on a tree in a variable numCherries. If you set it’s initial value to 0 — which is a pretty valid choice in almost all situations, you cannot really tell if you did not count yet or you counted zero cherries on a tree. But if you set it to nil before you count it, then you can know that you have not yet counted (when the value is indeed nil). In normal situations you would have to use another boolean variable to hold that status. You can use nil to represent the absence of a value.

您可以使用可选选项来表示可能丢失,未知或已删除的数据。 例如,假设您要将一棵树上的樱桃数量存储在变量numCherries 。 如果将其初始值设置为0,这几乎是所有情况下的有效选择,那么您将无法真正确定是否还没有计数,或者您是否在树上计数了零个樱桃。 但是,如果您在计数之前将其设置为nil ,那么您可以知道您尚未计数(当该值的确为nil )。 在正常情况下,您将必须使用另一个布尔变量来保持该状态。 您可以使用nil表示缺少值。

为什么使用Optionals (Why use Optionals)

The Xcode compiler is very forgiving when you declare a variable as optional. It will help you along as you code reminding you to unwrap the variable before using it. It is such a pleasure to get these hints (in the form of build errors). Once you understand whether your variable should be an optional, then there is no way that a missing value in an optional will cause your program to crash. In other words, it makes programming in swift more fun than it already is.

当您将变量声明为可选变量时,Xcode编译器非常宽容。 它会在您编写代码时提醒您,提醒您在使用变量之前先对其进行拆包。 很高兴获得这些提示(以构建错误的形式)。 一旦了解了变量是否应为可选变量,那么就无法避免可选变量中的缺失值导致程序崩溃。 换句话说,它使编程变得比以前更加有趣。

关于约翰 (About John)

John runs the Advanced iOS Programming meetup in Cupertino. Due to Covid-19 most of the future meetups will be online, so feel free to sign up. Even if you cannot attend live, you can watch the recordings later (coming soon).

John 在Cupertino 举办了 高级iOS编程 聚会。 由于Covid-19,大多数未来的聚会都将在线上进行,因此请随时注册。 即使您不能现场直播,也可以 稍后观看录音(即将推出)

翻译自: https://medium.com/swlh/optionals-in-swift-c53cf5535b9

swift 闭包 可选项

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值