如何在Swift中检查Enum类型?

时间:2016-01-11 17:06:44

标签: swift enums

我正在编写一个序列化程序,可以序列化枚举和其他Swift类型(字符串,对象等)。所以我需要检查传递给我的序列化程序的Any参数是否是Enum或其他东西。似乎在Swift中执行此操作的唯一方法是使用反射。下面的代码是否合理或是否有更好的方法来检查枚举类型?

enum Things {
    case Thing1
    case Thing2
}

let something:Any = Things.Thing1
let mirror = Mirror(reflecting: something)
if (mirror.displayStyle == .Enum) {
    print("Reflected type is Enum") // works
}

2 个答案:

答案 0 :(得分:1)

enum Things {
    case Thing1
    case Thing2
}

let something:Any = Things.Thing1

something.dynamicType == Things.self // true

根据讨论更新..

protocol P {}
enum Things:P {
    case Thing1
    case Thing2
}
enum Things2:P{
    case Things21
}

let something:Any = Things.Thing1
something.dynamicType == Things.self // true
if let p = something as? P {
    print(true)
}

let somethingelse: Any = Things2.Things21
if let p = somethingelse as? P {
    print(true)
}

答案 1 :(得分:1)

由于Mirror.displayStyle是可选的枚举,因此最好在同一语句中使用条件展开和类型检查。

您可以使用Mirror.displayStyle方法扩展.equals,以便在您想要经常进行枚举检查时随时访问它。

extension Mirror.DisplayStyle {
    func equals(displayCase: Mirror.DisplayStyle) -> Bool {
        return self == displayCase
    }
}

enum Things {
    case Thing1
    case Thing2
}

let something:Any = Things.Thing1
let mirror = Mirror(reflecting: something)

/* short form: using nil coalescing and ternary conditional operator */
mirror.displayStyle?.equals(.Enum) ?? false ? print("Reflected type is an Enum") : ()

/* another option: or using if-let */
if let _ = mirror.displayStyle?.equals(.Enum) {
   print("Reflected type is an Enum")
}

请注意,您无需为此检查显式创建和存储Mirror实例,但可以在一个表达式中执行所有操作,对于something类型的Any实例:

Mirror(reflecting: something).displayStyle?.equals(.Enum) ?? false ? print("Reflected type is an Enum") : ()

最后,如果您只是根据不同DisplayStyle实例的Any情况做一些简单的操作,那么您可以创建一个函数来切换此枚举的不同情况。下面是"简单的动作"只打印案例。

//... 

func foo(mirror: Mirror) {
    if let dispStyle = mirror.displayStyle {
        switch(dispStyle) {
        case .Class: print("Reflected type is a Class")
        case .Collection: print("Reflected type is a Collection")
        case .Dictionary: print("Reflected type is a Dictionary")
        case .Enum: print("Reflected type is an Enum")
        case .Optional:  print("Reflected type is an Optional")
        case .Set:  print("Reflected type is a Set")
        case .Struct:  print("Reflected type is a Struct")
        case .Tuple:  print("Reflected type is a Tuple")
        }
    }
}

let something: Any = Things.Thing1
foo(Mirror(reflecting: something))

另见Language Reference for Mirror.DisplayStyle