Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
122 lines (82 sloc) 1.43 KB

Swift中optionals使用总结

  1. 变量声明
let optional: String? = "unicorn"
var optional2: Int?
let optionals: [String?] = ["unicorn", nil, "dragon"]
var optionals2: [Int]?
  1. if let
if let value = optional {

// 多变量
if let value = optional, let value2 = optional2 {

// 布尔值判断从句(boolean clause)
if let value = optional, value.hasSuffix("saurus") {
  1. guard
guard let value = optional else { 
  return
}
  1. while
while let value = optional {
  1. 空合运算((Nil Coalescing)
let value = optional ?? "nil"
  1. 强制解析
let value = optional!
  1. switch
switch optional {
case .some(let value):
  print(value)
case .none:
  print("nil")
}
  1. map()
let value = optional.map(String.init(describing:))
  1. flatMap()
let value = optional.flatMap(URL.init(string:))
  1. compactMap()
let values = optionals.compactMap { $0 }
  1. 类型转换
let value = optional as! String
  1. 可选链
let value = optional?.uppercased()
  1. for
for element in optionals {
  if let value = element {
  1. for case let
for case let optional? in optionals {
  1. forEach
optionals?.forEach { value in
  1. 错误转换成optional
try? aThrowingCall()
try! aThrowingCall()

参考: https://www.optionals.org

You can’t perform that action at this time.