SLMacros is a Swift package that provides two macros:
#URL("...")for creating validatedFoundation.URLvalues from string literals.@CaseIdentifiablefor making an enum conform toIdentifiableand generating a string-basedid.
#URL is a freestanding expression macro that accepts a static string literal and returns a URL.
It validates the value at compile time and emits an error when:
- the argument is not a string literal
- the string is not a valid absolute URL
Example:
import Foundation
import SLMacros
let website = #URL("https://example.com")This works well when you want URL values to be checked during compilation instead of failing later at runtime.
@CaseIdentifiable is an attached macro for enums. It:
- adds
Identifiableconformance - generates a
public var id: String - uses the enum case name as the identifier
Example:
import SLMacros
@CaseIdentifiable
enum Screen {
case home
case settings
case profile(userID: Int)
}The macro expands to behavior equivalent to:
extension Screen: Identifiable {}
extension Screen {
public var id: String {
switch self {
case .home:
"home"
case .settings:
"settings"
case .profile:
"profile"
}
}
}The macro emits diagnostics when:
- it is applied to something other than an enum
- the enum has no cases
- the enum already conforms to
Identifiable
You can install SLMacros in Xcode either from GitHub or by downloading the repository and adding it as a local package.
- Open your app project in Xcode.
- Choose
File > Add Package Dependencies... - Enter the package URL:
https://github.com/StewartLynch/SLMacros
- Choose the dependency rule you want, such as the latest version or a branch.
- Click
Add Package. - Add the
SLMacroslibrary product to the target that will use the macros.
- Download or clone the repository from github.com/StewartLynch/SLMacros.
- Open your app project in Xcode.
- Choose
File > Add Package Dependencies... - Click
Add Local... - Select the downloaded
SLMacrosfolder. - Add the
SLMacroslibrary product to the target that will use the macros.
Once the package has been added, Xcode will make the macros available to any target linked against the SLMacros product.
After adding the package to your target, import the module where you want to use the macros:
import Foundation
import SLMacrosThen use them like this:
import Foundation
import SLMacros
struct Link {
let url = #URL("https://example.com")
}
@CaseIdentifiable
enum Route {
case home
case profile(userID: Int)
}- Xcode with Swift macro support
- Swift 6 package tools as configured in Package.swift