Given the method
func enumCaseCount<T: Hashable>(ofType type: T.Type) -> Int {
// Needed check if type is an enum type
return 3
}
Used as follows
private enum SimpleEnum: String {
case a = "A"
case b = "B"
case c = "C"
}
enumCaseCount(ofType: SimpleEnum.self)
Any idea how to check if the given metatype is an enum?
Classes can be tested this way
class Test {}
Test.self is AnyClass // returns true
For the fun of it, as a (workaround) hack, we could instantiate an instance of
Tand perform runtime instrospection on it usingMirror, specifically itsdisplayStyleproperty. Before we proceed, we note that we'll only use this for debugging purposesI'll also point out that we're really chasing our tail here as we resort to runtime to query things known (by the compiler, at least) at compile time.
Anyway, first of all, I'll rename
enumCaseCount(...)toisEnum(...), as this question only covers querying whether a metatype is anenumor not. For similar (somewhat brittle) hacks to query the number of cases of a givenenum, see:Now, the generic placeholder
TinisEnum(...)only knows that it is a type conforming toHashable, which doesn't give us any straight-forward way to instantiate an instance ofT(ifHashableblueprinted, say, an initializerinit(), we'd could readily construct an instance ofTan perform runtime introspection upon it). Instead, we'll resort to manually allocating raw memory for a singleTinstance (UnsafeMutableRawPointer.allocate(bytes:alignedTo:)), binding it toT(bindMemory(to:capacity:)), and finally deallocating the memory (deallocate(bytes:alignedTo:)) once we've finished our runtime introspection of the instance referenced to by the pointer to the bound memory. As for the runtime introspection, we simply useMirrorto check whether itsdisplayStyleisenumor not.Example usage: