An enumeration is a sub-set of contextually valid values of some super type, and of course you may wish to iterate over all valid values in your context.
Starting with Swift 4.2 (with Xcode 10), just add protocol conformance to CaseIterable
to benefit from allCases
:
extension Suit: CaseIterable {}
Then this will print all possible values:
Suit.allCases.forEach { print($0.rawValue) }
Compatibility with earlier Swift versions (3.x and 4.x)
Just mimic the Swift 4.2 implementation:
#if !swift(>=4.2) public protocol CaseIterable { associatedtype AllCases: Collection where AllCases.Element == Self static var allCases: AllCases { get } } extension CaseIterable where Self: Hashable { static var allCases: [Self] { return [Self](AnySequence { () -> AnyIterator<Self> in var raw = 0 var first: Self? return AnyIterator { let current = withUnsafeBytes(of: &raw) { $0.load(as: Self.self) } if raw == 0 { first = current } else if current == first { return nil } raw += 1 return current } }) } } #endif
Another Essentially the proposed solution is:
enum ProductCategory : String { case Washers = "washers", Dryers = "dryers", Toasters = "toasters" static let allValues = [Washers, Dryers, Toasters] } for category in ProductCategory.allValues{ //Do something }
Or made a utility function iterateEnum()
for iterating cases for arbitrary enum
types.
Here is the example usage:
enum Suit:String { case Spades = "♠" case Hearts = "♥" case Diamonds = "♦" case Clubs = "♣" } for f in iterateEnum(Suit) { println(f.rawValue) }
outputs:
♠ ♥ ♦ ♣