In this quick tutorial I'll show you how to get all the possible values for a Swift enum type with a generic solution written in Swift 4.


UPDATE: From Swift 4.2 you can simply conform to the CaseIterable protocol, and you'll get the allCases static property for free. 🎉🎉🎉

If you are targeting below Swift 4.2, feel free to use the following method:

Become a Patron!

First we need to define a new EnumCollection protocol, and then we'll make a protocol extension on it, so you don't have to write too much code at all.

From now on you only have to conform your enum types to the EnumCollection protocol and you can enjoy the brand new cases method and allValues property which will contain all the possible values for that given enumeration.

Note that the base type of the enumeration needs to be Hashable, but that's not a big deal. This solution is part of the CoreKit framework and it works like a charm.


External sources