freenode
Languages & Toolchains

Swift reviews macros that can grant self access in property initializers

SE-0539 would let accessor macros promise the compiler that an initializer expression will run only after self is fully available.

Swift Evolution has opened review of SE-0539, a proposal that would let attached macros declare whether a property initializer expression may legally refer to self. The change targets a long-standing mismatch: when a macro moves that expression into a later context such as a getter, the type checker still rejects self references because it evaluates the expression in its original location, before the enclosing instance exists.

The primary use case is macros that recreate or extend lazy initialization. A macro author would annotate the accessor role with an initialization: selfAvailable flag, promising that the expression will only be evaluated after the type is fully constructed. The compiler can then accept references to self and other instance members at the declaration site. Without the flag the existing conservative check remains, so macros that expand into init accessors or other early contexts continue to reject such access.

Proposal author dohle illustrated the gap with a @Lazy macro and with more elaborate examples such as a @Thumbnailed property that defers image processing until first read, or accessors that log, clamp, or back storage in a dictionary. Reviewers asked whether the feature is too narrowly tailored to Lazy-style macros and whether an underscored experimental spelling would be preferable. Naming of the new role parameter also drew comment; selfAvailable was favored over spellings that expose compiler internals such as autoclosure treatment.

The review, managed by Tony Allevato, runs through 16 August 2026. The addition is opt-in, confined to accessor macro role declarations, and invisible to ordinary Swift code.