Swift可选型(optional)各种用法示例
原文:optionals
the optionals
1 | let optional: String? = "unicorn" |
if let
1 | if let value = optional { |
multiple variables
1 | if let value = optional, let value2 = optional2 { |
boolean clause
1 | if let value = optional, value.hasSuffix("saurus") { |
guard
1 | guard let value = optional else { |
while let
1 | while let value = optional { |
nil coalescing
1 | let value = optional ?? "nil" |
force unwrapping
1 | let value = optional! |
switch block
1 | switch optional { |
map()
1 | let value = optional.map(String.init(describing:)) |
flatMap()
1 | let value = optional.flatMap(URL.init(string:)) |
compactMap()
1 | let values = optionals.compactMap { $0 } |
type casting
1 | let value = optional as! String |
optional chaining
1 | let value = optional?.uppercased() |
for loop
1 | for element in optionals { |
for case let
1 | for case let optional? in optionals { |
for case .some
1 | for case .some(let value) in optionals { |
forEach
1 | optionals2?.forEach { value in |
assignment
1 | assigns if the optional has a value |
pattern matching
1 | switch optional { |
enums
1 | enum Animal { |
switching with associated optionals
1 | let enumValue = Animal.pet(type: optional) |
switching on optional enums
1 | let enumValue2: Animal? = nil |
参考
Apple Developer Documentation: Optional
The Complete Guide to Optionals in Swift
Swift optionals explained simply
Extending optionals in Swift