Storing Constant Values in Swift: Creating a Constants File
Introduction:
This article explores different methods of storing constant values in a shared file in Swift, focusing on using structs and enums.
Using Struct for Constant Values:
To store constant values, we can employ a struct with type properties. In Swift, type properties are accessed using the static keyword. Here’s an example:
struct FontSize {
static let headline = 34
static let subhead = 18
}
Using Caseless Enum for Constant Values:
Alternatively, we can use a caseless enum, which is an enum without cases, solely consisting of static properties. This approach avoids accidental initialization. However, it lacks type safety and allows duplicate values. Example:
enum FontSize {
static let headline = 34
static let subhead = 18
}
Using Enum with Raw Values:
To enhance type safety and prevent duplicate values, an enum with raw values is preferable for storing constants. Example:
enum FontSize: Double {
case headline = 34
case body = 18
}
Leveraging callAsFunction:
Starting from Swift 5.2, the callAsFunction feature allows creating callable values. We can leverage this to access enum values without explicitly using rawValue. Here’s an example:
protocol Functionable {
associatedtype T
func callAsFunction() -> T
}
extension Functionable where Self: RawRepresentable {
func callAsFunction() -> Self.RawValue {
return rawValue
}
}
enum FontSize: Double, Functionable {
case headline = 34
case body = 18
}
// Accessing enum value without rawValue
let headlineValue = FontSize.headline()
Conclusion:
By utilizing enums with callAsFunction(), we can create a unique and type-safe approach to store constant values. This helps prevent accidental initialization and duplicates, ensuring code reliability and maintainability.
We welcome your thoughts and suggestions on this approach.
Please refer part 2 of this series where we are using another approach using macros — https://medium.com/@vinodh_36508/part-2-enhancing-constant-value-management-in-swift-enums-using-macros-2f00de2a896f
Keep up with us on social media:
LinkedIn: https://www.linkedin.com/company/evangelist-apps-limited/
Twitter: https://twitter.com/EvangelistSW/