Avatar
swiftbot BOT 5/17/2018 2:44 AM
(edited)
Author icon
noppe
import Foundation protocol EnumCollection: Hashable { static var all: [Self] { get } } extension EnumCollection { static func cases() -> AnySequence<Self> { typealias SelfType = Self return AnySequence { () -> AnyIterator<SelfType> in var raw = 0 return AnyIterator { let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: SelfType.self, capacity: 1) { $0.pointee } } guard current.hashValue == raw else { return nil } raw += 1 return current } } } static var all: [Self] { return Array(self.cases()) } } enum SampleEnum: String, EnumCollection { case hoge = "hoge" case foo case bar = "BAR" } print(SampleEnum.all)
Version:
swift-4.1-RELEASE
Output:
[main.SampleEnum.hoge, main.SampleEnum.foo, main.SampleEnum.bar]
Error:
Version:
swift-4.0-RELEASE
Output:
[main.SampleEnum.hoge, main.SampleEnum.foo, main.SampleEnum.bar]
Error:
Version:
swift-3.1.1-RELEASE
Output:
[main.SampleEnum.hoge, main.SampleEnum.foo, main.SampleEnum.bar]
Error: