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