Swift 中的可选值是什么? [英] What is an optional value in Swift?

查看:26
本文介绍了Swift 中的可选值是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Apple 的文档:

<块引用>

您可以结合使用 iflet 来处理可能缺失的值.这些值表示为可选项.可选值要么包含一个值,要么包含 nil 以指示该值丢失.在值的类型后写一个问号 (?) 以将该值标记为可选.

为什么要使用可选值?

解决方案

Swift 中的 optional 是一种可以保存值或不保存值的类型.可选项是通过将 ? 附加到任何类型来编写的:

变量名:字符串?=伯蒂"

Optionals(连同泛型)是 Swift 中最难理解的概念之一.由于它们的编写和使用方式,很容易对它们的含义产生错误的认识.将上面的可选项与创建普通字符串进行比较:

var name: String = "Bertie";//没有?"在字符串之后

从语法上看,可选字符串与普通字符串非常相似.它不是.可选字符串不是带有一些可选"字符串的字符串.设置开启.它不是一种特殊的 String.String 和 optional String 是完全不同的类型.

最重要的一点是:可选是一种容器.一个可选的字符串是一个容器,它可能包含一个字符串.可选的 Int 是一个可能包含 Int 的容器.将可选项视为一种包裹.在您打开它(或用可选语言中的解包")之前,您不会知道它是否包含某些东西.

您可以看到如何实现可选项 在 Swift 标准库中键入Optional"进入任何 Swift 文件,然后按住 ⌘ 键单击它.这是定义的重要部分:

enum Optional{情况 无案例一些(包裹)}

Optional 只是一个 enum,它可以是两种情况之一:.none.some.如果它是 .some,则有一个关联值,在上面的示例中,它是 String Hello".可选使用泛型为关联值提供类型.可选字符串的类型不是 String,而是 Optional,或者更准确地说是 Optional.

Swift 使用可选项所做的一切都是让阅读和编写代码更加流畅的魔法.不幸的是,这掩盖了它实际工作的方式.稍后我会介绍一些技巧.

注意:我会经常讨论可选变量,但也可以创建可选常量.我用它们的类型标记了所有变量,以便更容易理解正在创建的类型类型,但您不必在自己的代码中这样做.


如何创建选项

要创建一个可选的,在你想要包装的类型后面附加一个 ?.任何类型都可以是可选的,甚至是您自己的自定义类型.类型和 ? 之间不能有空格.

变量名:字符串?=鲍勃"//创建一个包含Bob"的可选字符串;var peter:人?= Person()//一个可选的Person";(自定义类型)//一个带有 String 和可选 String 属性的类类汽车{var modelName: String//必须存在var internalName:字符串?//可能存在也可能不存在}


使用选项

你可以将一个 optional 与 nil 进行比较,看看它是否有值:

变量名:字符串?=鲍勃"name = nil//设置 name 为 nil,没有值如果名称 != nil {打印(有一个名字")}if name == nil {//也可以使用else";打印(名称没有价值")}

这有点令人困惑.这意味着可选项要么是一回事,要么是另一回事.它要么是零,要么是鲍勃".这不是真的,可选项不会转换成其他东西.将它与 nil 进行比较是一种使代码更易于阅读的技巧.如果一个 optional 等于 nil,这仅仅意味着枚举当前设置为 .none.


只有可选项可以为 nil

如果您尝试将非可选变量设置为 nil,则会出现错误.

var red: String = "Red";red = nil//错误:无法将 nil 分配给类型 'String'

另一种看待可选项的方式是作为普通 Swift 变量的补充.它们是保证具有值的变量的对应物.Swift 是一种谨慎的语言,它讨厌歧义.大多数变量被定义为非可选,但有时这是不可能的.例如,想象一个视图控制器从缓存或网络加载图像.在创建视图控制器时它可能有也可能没有该图像.没有办法保证 image 变量的值.在这种情况下,您必须将其设为可选.它以 nil 开头,当检索到图像时,可选项获取一个值.

使用可选项揭示了程序员的意图.与 Objective-C 相比,任何对象都可能为 nil,Swift 需要你清楚什么时候一个值可能丢失,什么时候保证存在.


要使用可选项,您可以解开"它

一个可选的String 不能代替实际的String.要在可选项中使用包装的值,您必须解开它.解开可选项的最简单方法是在可选项名称后添加 !.这称为强制展开".它返回可选中的值(作为原始类型),但如果可选是 nil,则会导致运行时崩溃.在展开之前,您应该确保有一个值.

变量名:字符串?=鲍勃"让 unwrappedName: String = name!打印(解包名称:(解包名称)")姓名 = 无让 nilName: String = name!//运行时崩溃.没想到是零.


检查和使用可选

因为在解包和使用可选项之前你应该总是检查 nil,这是一个常见的模式:

var mealPreference:字符串?=素食主义者"如果膳食偏好!= nil {让 unwrappedMealPreference: String = mealPreference!print("Meal: (unwrappedMealPreference)")//或者做一些有用的事情}

在这个模式中,你检查一个值是否存在,然后当你确定它存在时,你强制将它解包成一个临时常量来使用.因为这是一件很常见的事情,Swift 提供了一个使用if let"的快捷方式.这称为可选绑定".

var mealPreference:字符串?=素食主义者"如果让 unwrappedMealPreference: String = mealPreference {打印(膳食:(unwrappedMealPreference)")}

这会创建一个临时常量(或变量,如果您将 let 替换为 var),其范围仅在 if 的大括号内.因为不得不使用像unwrappedMealPreference"这样的名字.或realMealPreference"是个负担,Swift 允许你重用原来的变量名,在括号范围内创建一个临时的

var mealPreference:字符串?=素食主义者"如果让mealPreference:字符串=mealPreference{print("Meal: (mealPreference)")//与其他的mealPreference分开}

以下是一些代码来演示使用了不同的变量:

var mealPreference:字符串?=素食主义者"如果 var mealPreference: String = mealPreference {print("Meal: (mealPreference)")//mealPreference 是一个字符串,而不是一个字符串?mealPreference = 牛肉"//对原图没有影响}//这是原始的mealPreferenceprint("Meal: (mealPreference)")//打印 "Meal: Optional("Vegetarian")";

可选绑定的工作原理是检查可选是否等于 nil.如果没有,它将可选项解包到提供的常量中并执行块.在 Xcode 8.3 及更高版本 (Swift 3.1) 中,尝试打印这样的可选项会导致无用的警告.使用可选的 debugDescription 使其静音:

print("(mealPreference.debugDescription)")


可选项有什么用?

Optionals 有两个用例:

  1. 可能会失败的事情(我期待某事,但我一无所获)
  2. 现在什么都没有的事情,但以后可能会发生(反之亦然)

一些具体的例子:

  • 一个属性可以存在也可以不存在,比如Person类中的middleNamespouse
  • 一种可以返回值或不返回值的方法,例如在数组中搜索匹配项
  • 一种可以返回结果或获取错误但不返回任何内容的方法,例如尝试读取文件的内容(通常返回文件的数据)但文件不存在
  • 委托属性,不必总是设置,一般在初始化后设置
  • 对于weak 类中的属性.他们指向的东西可以随时设置为nil
  • 可能需要释放大量资源以回收内存
  • 当您需要一种方法来知道何时设置了值(数据尚未加载 > 数据)而不是使用单独的 dataLoaded Boolean

Objective-C 中不存在可选项,但有一个等效的概念,返回 nil.可以返回对象的方法可以返回 nil.这被认为是指没有有效对象".并且通常用于表示出现问题.它仅适用于 Objective-C 对象,不适用于基元或基本 C 类型(枚举、结构).Objective-C 通常有专门的类型来表示这些值的缺失(NSNotFound 实际上是 NSIntegerMaxkCLLocationCoordinate2DInvalid 表示无效坐标,-1 或一些负值也被使用).编码人员必须了解这些特殊值,因此必须为每个案例记录和学习它们.如果方法不能将 nil 作为参数,则必须对此进行记录.在 Objective-C 中,nil 是一个指针,就像所有对象都被定义为指针一样,但是 nil 指向一个特定的(零)地址.在 Swift 中,nil 是一个字面量,表示没有某种类型.


对比nil

您曾经可以将任何可选项用作 Boolean:

let LeatherTrim:CarExtras?= 零如果皮革修剪{价格 = 价格 + 1000}

在更新的 Swift 版本中,您必须使用 leatherTrim != nil.为什么是这样?问题在于 Boolean 可以包含在可选中.如果你有这样的 Boolean:

var ambiguous: Boolean?= 假

它有两种假",一种是没有值的,另一种是有值但值为false.Swift 讨厌歧义,所以现在你必须总是检查一个可选的 nil.

您可能想知道可选的 Boolean 有什么意义?与其他可选项一样, .none 状态可能表明该值是未知的.网络呼叫的另一端可能有一些东西需要一些时间来轮询.可选布尔值也称为三值布尔值"


Swift 技巧

Swift 使用了一些技巧来允许选项起作用.考虑这三行看起来普通的可选代码;

var宗教隶属关系:字符串?=拉斯塔法里教"宗教归属 = 无如果宗教隶属关系 != nil { ... }

这些行都不应该编译.

  • 第一行使用两种不同类型的字符串字面量设置可选字符串.即使这是一个 String 类型也不同
  • 第二行设置一个可选的String为nil,两种不同的类型
  • 第三行将一个可选字符串与 nil 进行比较,两种不同的类型

我将详细介绍允许这些行工作的选项的一些实现细节.


创建可选

使用 ? 创建一个可选的语法糖,由 Swift 编译器启用.如果你想长期这样做,你可以创建一个这样的可选:

变量名:可选<字符串>= 可选(鲍勃")

这将调用 Optional 的第一个初始化器,public init(_ some: Wrapped),它从括号内使用的类型推断出可选的关联类型.>

创建和设置可选的更长的方法:

var serialNumber:String?= 可选.无serialNumber = Optional.some(1234")打印((serialNumber.debugDescription)")


设置一个可选的nil

您可以创建一个没有初始值的可选项,也可以创建一个初始值为 nil 的选项(两者的结果相同).

变量名:字符串?变量名称:字符串?= 零

允许选项等于 nil 由协议 ExpressibleByNilLiteral(以前命名为 NilLiteralConvertible)启用.可选是用 Optional 的第二个初始化器,public init(nilLiteral: ()) 创建的.文档说你不应该将 ExpressibleByNilLiteral 用于除可选之外的任何东西,因为这会改变你代码中 nil 的含义,但可以这样做:

class Clint: ExpressibleByNilLiteral {变量名称:字符串?必需的 init(nilLiteral: ()) {name =无名之人"}}let clint: Clint = nil//通常会报错打印((clint.name)")

同样的协议允许你将一个已经创建的可选设置为 nil.虽然不推荐,但你可以直接使用 nil 字面量初始化器:

变量名:可选<字符串>= Optional(nilLiteral: ())


比较一个可选项和 nil

Optionals 定义了两个特殊的==";和!="运算符,您可以在 Optional 定义中看到.第一个 == 允许您检查任何可选项是否等于 nil.如果关联类型相同,则设置为 .none 的两个不同选项将始终相等.当您与 nil 进行比较时,Swift 在幕后创建了一个具有相同关联类型的 optional,设置为 .none 然后将其用于比较.

//Swift 与 nil 的实际比较var tuxedoRequired: 字符串?= 零让临时:可选<字符串>= 可选.无if tuxedoRequired == temp {//等价于 if tuxedoRequired == nil打印(tuxedoRequired 为 nil")}

第二个 == 运算符允许您比较两个选项.两者都必须是相同的类型,并且该类型需要符合 Equatable(允许与常规=="运算符进行比较的协议).Swift(大概)解开这两个值并直接比较它们.它还处理其中一个或两个选项是 .none 的情况.注意与 nil 文字比较的区别.

此外,它允许您将任何 Equatable 类型与该类型的可选包装进行比较:

让 numberToFind: Int = 23让 numberFromString: Int?= Int("23")//Optional(23)如果 numberToFind == numberFromString {print("It's a match!")//打印 "It's a match!";}

在幕后,Swift 在比较之前将非可选内容包装为可选内容.它也适用于文字 (if 23 == numberFromString {)

我说过有两个 == 运算符,但实际上还有第三个允许您将 nil 放在比较的左侧

if nil == name { ... }


命名可选

Swift 没有约定将可选类型命名为与非可选类型不同的名称.人们避免在名称中添加一些内容来表明它是一个可选类型(如optionalMiddleName"或possibleNumberAsString"),并让声明表明它是一个可选类型.当你想命名一些东西来保存可选项的值时,这会变得很困难.名称中间名"暗示它是一个 String 类型,因此当您从中提取 String 值时,通常会以actualMiddleName"之类的名称结尾.或解开中间名"或真实中间名".使用可选绑定并重用变量名来解决这个问题.


官方定义

来自 基础知识"在 Swift 编程语言中:

<块引用>

Swift 还引入了可选类型,用于处理没有值的情况.可选项说有一个值,它等于 x"或根本没有值".Optionals 类似于在 Objective-C 中使用 nil 和指针,但它们适用于任何类型,而不仅仅是类.Optional 比 Objective-C 中的 nil 指针更安全、更具表现力,并且是 Swift 许多最强大功能的核心.

Optionals 是 Swift 是一种类型安全语言这一事实​​的一个例子.Swift 可帮助您明确代码可以使用的值类型.如果您的代码的一部分需要 String,类型安全可以防止您错误地将 Int 传递给它.这使您能够在开发过程中尽早发现和修复错误.


最后,这是一首 1899 年关于可选项的诗:

昨天在楼梯上
我遇到了一个不在场的男人
他今天又没有出现
我希望,我希望他走开

Antigonish


更多资源:

From Apple's documentation:

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

Why would you want to use an optional value?

解决方案

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:

var name: String? = "Bertie"

Optionals (along with Generics) are one of the most difficult Swift concepts to understand. Because of how they are written and used, it's easy to get a wrong idea of what they are. Compare the optional above to creating a normal String:

var name: String = "Bertie" // No "?" after String

From the syntax it looks like an optional String is very similar to an ordinary String. It's not. An optional String is not a String with some "optional" setting turned on. It's not a special variety of String. A String and an optional String are completely different types.

Here's the most important thing to know: An optional is a kind of container. An optional String is a container which might contain a String. An optional Int is a container which might contain an Int. Think of an optional as a kind of parcel. Before you open it (or "unwrap" in the language of optionals) you won't know if it contains something or nothing.

You can see how optionals are implemented in the Swift Standard Library by typing "Optional" into any Swift file and ⌘-clicking on it. Here's the important part of the definition:

enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

Optional is just an enum which can be one of two cases: .none or .some. If it's .some, there's an associated value which, in the example above, would be the String "Hello". An optional uses Generics to give a type to the associated value. The type of an optional String isn't String, it's Optional, or more precisely Optional<String>.

Everything Swift does with optionals is magic to make reading and writing code more fluent. Unfortunately this obscures the way it actually works. I'll go through some of the tricks later.

Note: I'll be talking about optional variables a lot, but it's fine to create optional constants too. I mark all variables with their type to make it easier to understand type types being created, but you don't have to in your own code.


How to create optionals

To create an optional, append a ? after the type you wish to wrap. Any type can be optional, even your own custom types. You can't have a space between the type and the ?.

var name: String? = "Bob" // Create an optional String that contains "Bob"
var peter: Person? = Person() // An optional "Person" (custom type)

// A class with a String and an optional String property
class Car {
var modelName: String // must exist
var internalName: String? // may or may not exist
}


Using optionals

You can compare an optional to nil to see if it has a value:

var name: String? = "Bob"
name = nil // Set name to nil, the absence of a value
if name != nil {
    print("There is a name")
}
if name == nil { // Could also use an "else"
    print("Name has no value")
}

This is a little confusing. It implies that an optional is either one thing or another. It's either nil or it's "Bob". This is not true, the optional doesn't transform into something else. Comparing it to nil is a trick to make easier-to-read code. If an optional equals nil, this just means that the enum is currently set to .none.


Only optionals can be nil

If you try to set a non-optional variable to nil, you'll get an error.

var red: String = "Red"
red = nil // error: nil cannot be assigned to type 'String'

Another way of looking at optionals is as a complement to normal Swift variables. They are a counterpart to a variable which is guaranteed to have a value. Swift is a careful language that hates ambiguity. Most variables are define as non-optionals, but sometimes this isn't possible. For example, imagine a view controller which loads an image either from a cache or from the network. It may or may not have that image at the time the view controller is created. There's no way to guarantee the value for the image variable. In this case you would have to make it optional. It starts as nil and when the image is retrieved, the optional gets a value.

Using an optional reveals the programmers intent. Compared to Objective-C, where any object could be nil, Swift needs you to be clear about when a value can be missing and when it's guaranteed to exist.


To use an optional, you "unwrap" it

An optional String cannot be used in place of an actual String. To use the wrapped value inside an optional, you have to unwrap it. The simplest way to unwrap an optional is to add a ! after the optional name. This is called "force unwrapping". It returns the value inside the optional (as the original type) but if the optional is nil, it causes a runtime crash. Before unwrapping you should be sure there's a value.

var name: String? = "Bob"
let unwrappedName: String = name!
print("Unwrapped name: (unwrappedName)")

name = nil
let nilName: String = name! // Runtime crash. Unexpected nil.


Checking and using an optional

Because you should always check for nil before unwrapping and using an optional, this is a common pattern:

var mealPreference: String? = "Vegetarian"
if mealPreference != nil {
    let unwrappedMealPreference: String = mealPreference!
    print("Meal: (unwrappedMealPreference)") // or do something useful
}

In this pattern you check that a value is present, then when you are sure it is, you force unwrap it into a temporary constant to use. Because this is such a common thing to do, Swift offers a shortcut using "if let". This is called "optional binding".

var mealPreference: String? = "Vegetarian"
if let unwrappedMealPreference: String = mealPreference {
    print("Meal: (unwrappedMealPreference)") 
}

This creates a temporary constant (or variable if you replace let with var) whose scope is only within the if's braces. Because having to use a name like "unwrappedMealPreference" or "realMealPreference" is a burden, Swift allows you to reuse the original variable name, creating a temporary one within the bracket scope

var mealPreference: String? = "Vegetarian"
if let mealPreference: String = mealPreference {
    print("Meal: (mealPreference)") // separate from the other mealPreference
}

Here's some code to demonstrate that a different variable is used:

var mealPreference: String? = "Vegetarian"
if var mealPreference: String = mealPreference {
    print("Meal: (mealPreference)") // mealPreference is a String, not a String?
    mealPreference = "Beef" // No effect on original
}
// This is the original mealPreference
print("Meal: (mealPreference)") // Prints "Meal: Optional("Vegetarian")"

Optional binding works by checking to see if the optional equals nil. If it doesn't, it unwraps the optional into the provided constant and executes the block. In Xcode 8.3 and later (Swift 3.1), trying to print an optional like this will cause a useless warning. Use the optional's debugDescription to silence it:

print("(mealPreference.debugDescription)")


What are optionals for?

Optionals have two use cases:

  1. Things that can fail (I was expecting something but I got nothing)
  2. Things that are nothing now but might be something later (and vice-versa)

Some concrete examples:

  • A property which can be there or not there, like middleName or spouse in a Person class
  • A method which can return a value or nothing, like searching for a match in an array
  • A method which can return either a result or get an error and return nothing, like trying to read a file's contents (which normally returns the file's data) but the file doesn't exist
  • Delegate properties, which don't always have to be set and are generally set after initialization
  • For weak properties in classes. The thing they point to can be set to nil at any time
  • A large resource that might have to be released to reclaim memory
  • When you need a way to know when a value has been set (data not yet loaded > the data) instead of using a separate dataLoaded Boolean

Optionals don't exist in Objective-C but there is an equivalent concept, returning nil. Methods that can return an object can return nil instead. This is taken to mean "the absence of a valid object" and is often used to say that something went wrong. It only works with Objective-C objects, not with primitives or basic C-types (enums, structs). Objective-C often had specialized types to represent the absence of these values (NSNotFound which is really NSIntegerMax, kCLLocationCoordinate2DInvalid to represent an invalid coordinate, -1 or some negative value are also used). The coder has to know about these special values so they must be documented and learned for each case. If a method can't take nil as a parameter, this has to be documented. In Objective-C, nil was a pointer just as all objects were defined as pointers, but nil pointed to a specific (zero) address. In Swift, nil is a literal which means the absence of a certain type.


Comparing to nil

You used to be able to use any optional as a Boolean:

let leatherTrim: CarExtras? = nil
if leatherTrim {
    price = price + 1000
}

In more recent versions of Swift you have to use leatherTrim != nil. Why is this? The problem is that a Boolean can be wrapped in an optional. If you have Boolean like this:

var ambiguous: Boolean? = false

it has two kinds of "false", one where there is no value and one where it has a value but the value is false. Swift hates ambiguity so now you must always check an optional against nil.

You might wonder what the point of an optional Boolean is? As with other optionals the .none state could indicate that the value is as-yet unknown. There might be something on the other end of a network call which takes some time to poll. Optional Booleans are also called "Three-Value Booleans"


Swift tricks

Swift uses some tricks to allow optionals to work. Consider these three lines of ordinary looking optional code;

var religiousAffiliation: String? = "Rastafarian"
religiousAffiliation = nil
if religiousAffiliation != nil { ... }

None of these lines should compile.

  • The first line sets an optional String using a String literal, two different types. Even if this was a String the types are different
  • The second line sets an optional String to nil, two different types
  • The third line compares an optional string to nil, two different types

I'll go through some of the implementation details of optionals that allow these lines to work.


Creating an optional

Using ? to create an optional is syntactic sugar, enabled by the Swift compiler. If you want to do it the long way, you can create an optional like this:

var name: Optional<String> = Optional("Bob")

This calls Optional's first initializer, public init(_ some: Wrapped), which infers the optional's associated type from the type used within the parentheses.

The even longer way of creating and setting an optional:

var serialNumber:String? = Optional.none
serialNumber = Optional.some("1234")
print("(serialNumber.debugDescription)")


Setting an optional to nil

You can create an optional with no initial value, or create one with the initial value of nil (both have the same outcome).

var name: String?
var name: String? = nil

Allowing optionals to equal nil is enabled by the protocol ExpressibleByNilLiteral (previously named NilLiteralConvertible). The optional is created with Optional's second initializer, public init(nilLiteral: ()). The docs say that you shouldn't use ExpressibleByNilLiteral for anything except optionals, since that would change the meaning of nil in your code, but it's possible to do it:

class Clint: ExpressibleByNilLiteral {
    var name: String?
    required init(nilLiteral: ()) {
        name = "The Man with No Name"
    }
}

let clint: Clint = nil // Would normally give an error
print("(clint.name)")

The same protocol allows you to set an already-created optional to nil. Although it's not recommended, you can use the nil literal initializer directly:

var name: Optional<String> = Optional(nilLiteral: ())


Comparing an optional to nil

Optionals define two special "==" and "!=" operators, which you can see in the Optional definition. The first == allows you to check if any optional is equal to nil. Two different optionals which are set to .none will always be equal if the associated types are the same. When you compare to nil, behind the scenes Swift creates an optional of the same associated type, set to .none then uses that for the comparison.

// How Swift actually compares to nil
var tuxedoRequired: String? = nil
let temp: Optional<String> = Optional.none
if tuxedoRequired == temp { // equivalent to if tuxedoRequired == nil
    print("tuxedoRequired is nil")
}

The second == operator allows you to compare two optionals. Both have to be the same type and that type needs to conform to Equatable (the protocol which allows comparing things with the regular "==" operator). Swift (presumably) unwraps the two values and compares them directly. It also handles the case where one or both of the optionals are .none. Note the distinction between comparing to the nil literal.

Furthermore, it allows you to compare any Equatable type to an optional wrapping that type:

let numberToFind: Int = 23
let numberFromString: Int? = Int("23") // Optional(23)
if numberToFind == numberFromString {
    print("It's a match!") // Prints "It's a match!"
}

Behind the scenes, Swift wraps the non-optional as an optional before the comparison. It works with literals too (if 23 == numberFromString {)

I said there are two == operators, but there's actually a third which allow you to put nil on the left-hand side of the comparison

if nil == name { ... }


Naming Optionals

There is no Swift convention for naming optional types differently from non-optional types. People avoid adding something to the name to show that it's an optional (like "optionalMiddleName", or "possibleNumberAsString") and let the declaration show that it's an optional type. This gets difficult when you want to name something to hold the value from an optional. The name "middleName" implies that it's a String type, so when you extract the String value from it, you can often end up with names like "actualMiddleName" or "unwrappedMiddleName" or "realMiddleName". Use optional binding and reuse the variable name to get around this.


The official definition

From "The Basics" in the Swift Programming Language:

Swift also introduces optional types, which handle the absence of a value. Optionals say either "there is a value, and it equals x" or "there isn’t a value at all". Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.


To finish, here's a poem from 1899 about optionals:

Yesterday upon the stair
I met a man who wasn’t there
He wasn’t there again today
I wish, I wish he’d go away

Antigonish


More resources:

这篇关于Swift 中的可选值是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆