Enums Static Members Explained in Swift
An enum with static members can be an incredibly useful way to logically group constants or manage configuration values.
Here’s an example!
enum API {
static let baseURL = "https://api.myexampleapi.com"
enum Endpoint {
static let login = "/user/login"
static let signup = "/user/signup"
static let profile = "/user/profile"
}
}
let url = URL(string: API.baseURL + API.Endpoint.login)
print(url!) // result: https://api.myexampleapi.com/user/login
In this code, the API enum has a static member that’s a constant named baseURL.
Then it has a nested enum named Endpoint, which has three static constant members named login, signup and profile.
Next, URL(string:) initializes a URL instance from the provided string. Here, it creates a URL from the values stored in the API enum and stores the resulting string in the constant named url.
Note: URL(string:) is an Optional that returns nil if the string doesn’t represent a valid URL.
Finally, we unwrap the Optional url and print it.
This approach to using enums is beneficial because it allows for logical grouping of API-related constants, while the nested Endpoint adds further categorisation, helping to keep the code organised and clean.