Swift enumerations
Enumerations or Enums are a way to define your own kind of value, you can define the data type and then the values that it holds.
enum Roles {
case admin
case user
case guest
}
Switch statement
Enums can be used to match with switch statements as we can sew below.
enum Roles {
case admin
case user
case guest
}
func logUserRole(role roles: Roles) {
switch roles {
case admin:
print("This is an admin user.")
case user:
print("This is a regular user.")
default:
print("This is a guest user.")
}
}
logUserRole(role: .guest)
If its not appropriate to provide a case for all enums Swift allows us to provide a "default" case.
Raw values
Raw values allows us to attach a value to our enum cases. These cases can be a string, integer, or any floating-point, just make sure the values are of type we set.
enum Roles: String {
case admin = "Administrator user"
case user = "Regular user"
case guest = "Guest user"
}
let role: Roles = .admin
print(role.rawValue)
Caseiterable
Using caseiterable makes our enum confirm to the CaseIterable
protocol which gives us access to specific properties like "allCases" & "AllCases". With caseiterable our enum gets put into a collection
which we can then use.
enum Roles: CaseIterable {
case admin, user, guest
}
print(Roles.allCases.count)
In the example above we have used "allCases" property to print out the number of cases in the enum collection.
enum Roles: String, CaseIterable {
case admin = "Administrator user"
case user = "Regular user"
case guest = "Guest user"
}
print(Roles.allCases.count)
for role in Roles.allCases {
print(role.rawValue)
}
In the example above we have used "allCases" property to print out the eawValue of each case in the enum collection.
Pro tip: Enums can have
methods
,subscripts
, andcomputed properties
but not thestored properties
.
Associated values
Associated values are used for storing specific values in our enum cases. The best part is we can store the values of any type and those value types can be different in each case.
enum MobileDevices {
case ios
case android
}
enum Components {
case backend(version: String)
case frontend(version: String)
case mobile(type: MobileDevices, version: String)
}
let component: Components = .mobile(type: .ios, version: "1.0.0")
print(component)
Conclusion
Enumerations are useful when it comes to deal with states, and we can quickly respond to different use cases by using switch
, and thanks to type-safety in Swift, we can safely wrangle any group of related values that come our way.