Skip to content

Instantly share code, notes, and snippets.

@gfontenot
Created June 8, 2018 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfontenot/2dc990148cad3f74c1731b7d4adb5e91 to your computer and use it in GitHub Desktop.
Save gfontenot/2dc990148cad3f74c1731b7d4adb5e91 to your computer and use it in GitHub Desktop.
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