I am trying to extend my PersistedModels like so:
@Versioned(3)
@Model
class MyType {
var name: String
init() { name = "hello" }
}
but it seems that SwiftData's@Model
macro is unable to read the properties added by my @Versioned
macro. I have tried changing the order and it ignores them regardless. version
is not added to schemaMetadata
and version
needs to be persisted. I was planning on using this approach to add multiple capabilities to my model types. Is this possible to do with macros?
VersionedMacro
/// A macro that automatically implements VersionedModel protocol
public struct VersionedMacro: MemberMacro, ExtensionMacro {
// Member macro to add the stored property directly to the type
public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self),
let firstArgument = argumentList.first?.expression else {
throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)")
}
let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces)
// Add the stored property with the version value
return [
"public private(set) var version: Int = \(raw: versionValue)"
]
}
// Extension macro to add static property
public static func expansion(
of node: SwiftSyntax.AttributeSyntax,
attachedTo declaration: some SwiftSyntax.DeclGroupSyntax,
providingExtensionsOf type: some SwiftSyntax.TypeSyntaxProtocol,
conformingTo protocols: [SwiftSyntax.TypeSyntax],
in context: some SwiftSyntaxMacros.MacroExpansionContext
) throws -> [SwiftSyntax.ExtensionDeclSyntax] {
guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self),
let firstArgument = argumentList.first?.expression else {
throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)")
}
let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces)
// We need to explicitly add the conformance in the extension
let ext = try ExtensionDeclSyntax("extension \(type): VersionedModel {}")
.with(\.memberBlock.members, MemberBlockItemListSyntax {
MemberBlockItemSyntax(decl: DeclSyntax(
"public static var version: Int { \(raw: versionValue) }"
))
})
return [ext]
}
}
VersionedModel
public protocol VersionedModel: PersistentModel {
/// The version of this particular instance
var version: Int { get }
/// The type's current version
static var version: Int { get }
}
Macro Expansion: