A Possible Vision for Macros in Swift

One area of Swift that I think could benefit from macro capabilities is literal initialization. It would be nice if these things were allowed:

let number: UInt24 = 0xFFFFFF
let string: EncodedString<Unicode.UTF32> = "hello world"
let version: Version = 1.0.0

struct UInt24 {
    var value: UInt32

    macro init(integerLiteral value: UInt32)
    // sets `self.value` to `value` if under 2^24, otherwise produces a compile-time error
}

struct EncodedString<Encoding: UnicodeCodec> {
    var contents: [Encoding.CodeUnit]

    macro init(stringLiteral value: String)
    // converts the `String` instance to an array of code units at compile time then sets `contents` to that array
}

struct Version {
    var major: Int
    var minor: Int
    var patch: Int

    macro init(numericLiteral major: Int, _ minor: Int, _ patch: Int)
    // initializes a `Version` based on a series of dot-separated numeric values
}
2 Likes