Practice exercises
Swift Macros is a complex topic, and it is a challenge to understand how to create a Swift macro without trying it yourself. Here are two exercises that can help you get started:
- Create an attached Swift macro that adds a function called
printVariables
. The function prints the list of the class properties and their values. - Create a freestanding macro called
#colorhex
that receives a hex color value and generates an RGB color expression. For example,#colorhex("#FFFFFF")
will generateColor(red: 0.0, green: 0.0,
blue: 0.0)
.
In addition, here are some links that can help you get more insights about Swift Macros:
- Swift Macros documentation from the Swift.org projects: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/macros/
- A GitHub repository about great Swift macros we can use and learn from: https://github.com/krzysztofzablocki/Swift-Macros