美文网首页
Swift可选型(optional)各种用法示例

Swift可选型(optional)各种用法示例

作者: 范范饭特稀 | 来源:发表于2019-04-15 12:49 被阅读0次

    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

    相关文章

      网友评论

          本文标题:Swift可选型(optional)各种用法示例

          本文链接:https://www.haomeiwen.com/subject/bkkuwqtx.html