Created
June 8, 2018 16:13
-
-
Save gfontenot/2dc990148cad3f74c1731b7d4adb5e91 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func assert(_ cond: @autoclosure () -> Bool) -> String { | |
if cond() { | |
return "✅" | |
} else { | |
return "❌" | |
} | |
} | |
#if !swift(>=4.2) | |
protocol KnownEnum: RawRepresentable, Hashable where RawValue == String { | |
static var allCases: [Self] { get } | |
} | |
#else | |
protocol KnownEnum: RawRepresentable, Hashable, CaseIterable where RawValue == String { | |
} | |
#endif | |
func cases<Enum: KnownEnum>(in flagType: Enum.Type) -> [Enum] { | |
let sequence = AnySequence { () -> AnyIterator<Enum> in | |
var raw = 0 | |
return AnyIterator { | |
let current: Enum = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: flagType, capacity: 1) { $0.pointee } } | |
dump(current) | |
dump(current.hashValue) | |
dump(raw) | |
guard current.hashValue == raw else { | |
return nil | |
} | |
raw += 1 | |
return current | |
} | |
} | |
return Array(sequence) | |
} | |
enum MyEnum: String, KnownEnum { | |
case foo | |
case bar | |
#if !swift(>=4.2) | |
static var allCases: [MyEnum] { return [.foo, .bar] } | |
#endif | |
} | |
let xs = cases(in: MyEnum.self) | |
assert(xs.count == 2) | |
xs.count | |
let ys = MyEnum.allCases | |
assert(ys.count == 2) | |
ys.count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment