Swift 关联值作为另一个枚举的关联值的枚举(嵌套关联值)
我有带有关联值的enumSwift 关联值作为另一个枚举的关联值的枚举(嵌套关联值),swift,Swift,我有带有关联值的enumFoo。EnumFoo用作另一个EnumCar的关联值。我想知道如何访问Foo的“嵌套”关联值,如下例所示: enum Foo: Equatable { case moo case zoo(String) } enum Car { case mar case dar(Foo) case gar(Foo) } func request(with type: Car) -> String { switch ty
Foo
。EnumFoo
用作另一个EnumCar
的关联值。我想知道如何访问Foo
的“嵌套”关联值,如下例所示:
enum Foo: Equatable {
case moo
case zoo(String)
}
enum Car {
case mar
case dar(Foo)
case gar(Foo)
}
func request(with type: Car) -> String {
switch type {
case .mar:
return "mar"
case .dar(let foo) where foo == .moo:
return "darmoo"
case .dar(let foo) where foo == .zoo(let value):
// how can I access the associated value of foo?
// This where syntax results in an error - Consecutive statements on a line must be separated by ';'
}
}
正如你正确地说的,它是嵌套的。所以,鸟巢!在开关内使用开关。这包括:
func request(with type: Car) -> String {
switch type {
case .mar:
return "mar"
case .dar(let foo):
switch foo {
case .moo: return "darmoo"
case .zoo(let s): return s
}
case .gar:
return "gar"
}
}
正如你正确地说的,它是嵌套的。所以,鸟巢!在开关内使用开关。这包括:
func request(with type: Car) -> String {
switch type {
case .mar:
return "mar"
case .dar(let foo):
switch foo {
case .moo: return "darmoo"
case .zoo(let s): return s
}
case .gar:
return "gar"
}
}
您可以使用模式匹配:
switch type {
case .mar:
return "mar"
case .dar(let foo) where foo == .moo:
return "darmoo"
case .dar(.moo):
return "dar: moo"
case let .dar(.zoo(value)):
return "dar: \(value)"
case .gar:
return "gar"
}
或者,如果您希望以与dar
和gar
相同的方式处理Foo
,您可以在一种情况下绑定Foo
:
switch type {
case .mar:
return "mar"
case .dar(let foo) where foo == .moo:
return "darmoo"
case let .dar(foo), let .gar(foo):
switch foo {
case .moo:
return "moo"
case let .zoo(value):
return value
}
}
您可以使用模式匹配:
switch type {
case .mar:
return "mar"
case .dar(let foo) where foo == .moo:
return "darmoo"
case .dar(.moo):
return "dar: moo"
case let .dar(.zoo(value)):
return "dar: \(value)"
case .gar:
return "gar"
}
或者,如果您希望以与dar
和gar
相同的方式处理Foo
,您可以在一种情况下绑定Foo
:
switch type {
case .mar:
return "mar"
case .dar(let foo) where foo == .moo:
return "darmoo"
case let .dar(foo), let .gar(foo):
switch foo {
case .moo:
return "moo"
case let .zoo(value):
return value
}
}