Swift 使用 类 在枚举上切换大小写
Swift Switch case on enum with Classes
这是我第一次使用这种枚举,枚举关联值类型,我需要根据对象的类型做一个switch
声明,我做不到,这是枚举:
enum TypeEnum {
case foo(FooClass)
case doo(DooClass)
case roo(RooClass)
}
我的对象有一个 TypeEnum
类型的变量,现在我需要检查枚举中的对象类型:
if let anObject = object as? TypeEnum {
switch anObject {
case .foo(???):
return true
...
default:
return false
}
}
我不知道用什么代替 ???
。 Xcode 告诉我放东西,但我只想打开 .foo
。
有什么想法吗?
您可以使用 let
捕获 associated values 为此:
switch anObject {
case .foo(let fooObj):
...
}
或者在 all 什么都没有,如果你根本不关心它们:
switch anObject {
case .foo:
...
}
请务必查看 the Swift Programming Language book 了解更多详情。
您可以使用下划线表示您对相关类型不感兴趣:
case .foo(_):
...
这是我第一次使用这种枚举,枚举关联值类型,我需要根据对象的类型做一个switch
声明,我做不到,这是枚举:
enum TypeEnum {
case foo(FooClass)
case doo(DooClass)
case roo(RooClass)
}
我的对象有一个 TypeEnum
类型的变量,现在我需要检查枚举中的对象类型:
if let anObject = object as? TypeEnum {
switch anObject {
case .foo(???):
return true
...
default:
return false
}
}
我不知道用什么代替 ???
。 Xcode 告诉我放东西,但我只想打开 .foo
。
有什么想法吗?
您可以使用 let
捕获 associated values 为此:
switch anObject {
case .foo(let fooObj):
...
}
或者在 all 什么都没有,如果你根本不关心它们:
switch anObject {
case .foo:
...
}
请务必查看 the Swift Programming Language book 了解更多详情。
您可以使用下划线表示您对相关类型不感兴趣:
case .foo(_):
...