I’m not sure if this topic has been discussed before. I searched but couldn’t find a similar proposal. If this has already been considered, I’d appreciate any references to previous discussions.
Summary
Swift currently supports typealias
, allowing developers to define aliases for existing types. This proposal suggests introducing valuealias
, a mechanism that enables defining constant values that are substituted inline by the compiler.
Motivation
In many scenarios, developers use global constants to define semantic values in code, for example:
let numberOfColumns = 3
However, even with let
, the compiler may treat this as a runtime constant rather than an inline substitution. The valuealias
feature would ensure that the replacement occurs at compile time, eliminating unnecessary memory usage or variable access overhead.
Proposed Syntax
The proposed syntax is similar to typealias
:
valuealias NUMBER_OF_COLUMNS = 3
Alternatively, with explicit type annotation:
valuealias NUMBER_OF_COLUMNS: Int = 3
This code:
let grid = Array(repeating: [], count: NUMBER_OF_COLUMNS)
Would be treated by the compiler as:
let grid = Array(repeating: [], count: 3)
Benefits
- Performance: Eliminates unnecessary accesses to global constants.
- Readability: Prevents magic numbers from appearing in the code.
- Safety: Ensures the value cannot be accidentally modified.
Considerations
valuealias
should support only compile-time known values.- It could potentially support constant expressions such as
valuealias MAX_SIZE = 2 * 1024
.
Conclusion
Introducing valuealias
would enhance Swift by providing a new tool for improving code expressiveness and optimization. It ensures compile-time value substitutions in a safe and intuitive way.