I was trying to implement Assign if different using freestanding macro and I did succeed but kind of cheating using a closure because the freestanding macro is expected to return and expression.
#assign(b, to: a, if: !=) for example is expanded to:
{
if a != b {
a = b
}
}()
Is this the only way to currently do this? Any plans to lift this restriction with another kind of freestanding macro?
@Douglas_Gregor
This is the only way to do this today. The early pitches for declaration macros had "code item" macros that could do this, and there's a partial implementation of the feature in the compiler behind an experimental feature flag (CodeItemMacros), but nobody has followed through with pitch/proposal/complete implementation. Personally, I haven't seen that many use cases for code-item macros vs. the other kinds, so I haven't looked into them further.
Doug
2 Likes
Jeremy_Gold
(Jeremy Goldschmidt)
3
Hello,
I have a use case for this kind of feature that might be valuable.
It's not possible to possible to wrap os log calls because OSLogMessage cannot be initiliazed from a String variable, it forces us to duplicate log lines to both log into Unified logging system and to Crashlytics for example.
I would like to use a macro to expand the boilerplate code that perform those 2 calls. It seems that only CodeItemMacro can achieve this but I might be wrong...
1 Like
moyerr
(Robbie Moyer)
4
I created a macro for this exact same use case, and ended up using the same immediately-executed closure strategy described in the original post here, in order to consolidate the two expressions down to a single one.
1 Like