【问题标题】:Extract associated value of enum case into a tuple将枚举案例的关联值提取到元组中
【发布时间】:2016-11-04 06:04:03
【问题描述】:

我知道如何使用 switch 语句提取枚举案例中的关联值:

enum Barcode {
    case upc(Int, Int, Int, Int)
    case quCode(String)
}
var productBarcode = Barcode.upc(8, 10, 15, 2)

switch productBarcode {
case  let .upc(one, two, three, four):
    print("upc: \(one, two, three, four)")
case .quCode(let productCode):
    print("quCode \(productCode)")
}

但我想知道是否有办法使用元组提取关联值。

我试过了

let (first, second, third, fourth) = productBarcode

正如预期的那样,它没有用。有没有办法将枚举案例的关联值转换为元组?还是不可能?

【问题讨论】:

    标签: ios swift enums tuples


    【解决方案1】:

    您可以使用if case let 的模式匹配来提取 一个特定枚举值的关联值:

    if case let Barcode.upc(first, second, third, fourth) = productBarcode {
        print((first, second, third, fourth)) // (8, 10, 15, 2)
    }
    

    if case let Barcode.upc(tuple) = productBarcode {
        print(tuple) // (8, 10, 15, 2)
    }
    

    【讨论】:

      【解决方案2】:

      你可以在这个场景中使用元组

      enum Barcode {
          case upc(Int, Int, Int, Int)
          case quCode(String)
      }
      var productBarcode = Barcode.upc(8, 10, 15, 2)
      
      switch productBarcode {
      case  let .upc(one, two, three, four):
          print("upc: \(one, two, three, four)")
      case .quCode(let productCode):
          print("quCode \(productCode)")
      }
      
      
      typealias tupleBarcode = (one:Int, two:Int,three: Int, three:Int)
      
      switch productBarcode {
      case  let .upc(tupleBarcode):
          print("upc: \(tupleBarcode)")
      case .quCode(let productCode):
          print("quCode \(productCode)")
      }
      

      upc: (8, 10, 15, 2)

      upc: (8, 10, 15, 2)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多