- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 321字
- 2021-07-02 23:54:24
Optionals
Swift provides optionals so they can be used in situations where a value may be absent. An optional will have some or none values. The ? symbol is used to define a variable as optional. Consider the following example:
// Optional value either contains a value or contains nil
var optionalString: String? = "A String literal"
optionalString = nil
The ! symbol can be used to forcefully unwrap the value from an optional. For instance, the following example forcefully unwraps the optionalString variable:
optionalString = "An optional String"
print(optionalString!)
Force unwrapping the optionals may cause errors if the optional does not have a value, so it is not recommended to use this approach as it is very hard to be sure if we are going to have values in optionals in different circumstances. The better approach would be to use the optional binding technique to find out whether an optional contains a value. Consider the following example:
let nilName: String? = nil
if let familyName = nilName {
let greetingfamilyName = "Hello, Mr. \(familyName)"
} else {
// Optional does not have a value
}
Optional chaining is a process to query and call properties, methods, and subscripts on an optional that might currently be nil. Optional chaining in Swift is similar to messaging nil in Objective-C, but in a way that works for any type and can be checked for success or failure. Consider the following example:
class Residence {
var numberOfRooms = 1
}
class Person {
var residence: Residence?
}
let jeanMarc = Person()
// This can be used for calling methods and subscripts through optional chaining too
if let roomCount = jeanMarc.residence?.numberOfRooms {
// Use the roomCount
}
In this example, we were able to access numberOfRooms, which was a property of an optional type (Residence) using optional chaining.
Optionals and optional binding and chaining will be covered in detail in Chapter 7, Dealing with Optionals.
- 計算機組成原理與接口技術:基于MIPS架構實驗教程(第2版)
- 數據分析實戰:基于EXCEL和SPSS系列工具的實踐
- Architects of Intelligence
- 企業大數據系統構建實戰:技術、架構、實施與應用
- Python廣告數據挖掘與分析實戰
- Libgdx Cross/platform Game Development Cookbook
- Dependency Injection with AngularJS
- Starling Game Development Essentials
- Learning Proxmox VE
- 從0到1:JavaScript 快速上手
- ZeroMQ
- 白話大數據與機器學習
- IPython Interactive Computing and Visualization Cookbook(Second Edition)
- Augmented Reality using Appcelerator Titanium Starter
- Hadoop 3實戰指南