How to get a random enum case from your custom enum type in Swift 4.2?
It is useful to map values returned from APIs to custom enum types if you know the values that are expected. Below is an example where we want to map string values that define the vendor name into a custom enum VendorType:
The above code will map the string value apple to the corresponding enum type VendorType.apple. Let’s go one step further. Since Xcode 10+ or Swift 4.2, you are able to iterate through all your available enum cases like below:
The change needed above to get all the cases, your custom enum had to conform to the CaseIterable protocol in step 1. You will then be able to access all the cases via the computed property allCases in step 2.
You are also able to retrieve a random case from your custom enum via randomElement function:
From Apple’s documentation about CaseIterable:
Types that conform to the
CaseIterableprotocol are typically enumerations without associated values. When using a
CaseIterabletype, you can access a collection of all of the type’s cases by using the type’s
WHERE TO GO FROM HERE?
You can read up on CaseIterable on Apple’s documentation.