如何获取属性值枚举



我有一个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"不能用作实例成员">

对于ab,变量的类型都是TestEnum。变量表示的确切情况没有在类型中编码。因此,您无法访问枚举大小写变量的关联值。

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

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

您可以使用模式匹配来访问值。(参见图案文档(

使用开关

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)")
}

最新更新