【问题标题】:How can I get the property value enum?如何获取属性值枚举?
【发布时间】:2020-12-31 15:51:47
【问题描述】:

我有一个包含 2 个案例的 Enum,每个案例都以 String 和 Int 作为属性:

 public enum TestEnum {
     case case1(String, Int? = nil)
     case case2(String, Int? = nil)
 }

我创建了一个值为 case1 和这两个属性的枚举:

let e = TestEnum.case1("abc", 123)

我的问题是如何获得

我试过了

        let a = e.case1.0 // expect to get 'abc' back
        let b = e.case1.1 // expect to get '123' back
        
        print ("\(a)")
        print ("\(b)")

但是我得到编译错误'Enum case 'case1' cannot be used as an instance member'

【问题讨论】:

  • 解决方案已经写在下面了。我想说的是枚举的关联值不是元组。因此你不能像元组一样访问。在您的情况下,e 已经等于 .case1 及其关联值。 e.case1 会报错,因为 e 本身就是 case1。

标签: swift enums


【解决方案1】:

ab 的变量类型均为 TestEnum。变量所代表的确切情况未在类型中编码。因此,您无法访问枚举 case 变量的关联值。

相反,您需要使用 if case let 有条件地转换枚举 case 并将其关联的值分配给变量。

let a = TestEnum.case1("a", 1)
if case let .case1(string, int) = a {
    print(string, int)
}

【讨论】:

    【解决方案2】:

    您可以使用模式匹配来访问这些值。 (参见patterns 文档)

    使用开关

    switch e {
    case .case1(let stringValue, let intValue):
        print("stringValue: \(stringValue), intValue: \(intValue)")
    default:
        break
    }
    

    如果

    if case .case1(let stringValue, let intValue) = e {
        print("stringValue: \(stringValue), intValue: \(intValue)")
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-20
      • 1970-01-01
      • 2011-02-16
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多