-
Notifications
You must be signed in to change notification settings - Fork 0
/
RelationshipMacro.swift
43 lines (32 loc) · 1.19 KB
/
RelationshipMacro.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Created by David Spooner
*/
import SwiftSyntax
import SwiftSyntaxMacros
/// RelationshipMacro enables defining NSRelationshipDescriptions from compatible variables of a managed object class.
public struct RelationshipMacro : ManagedPropertyMacro
{
// ManagedPropertyMacro
static func inferredMetadataConstructorArguments(for info: StoredPropertyInfo, with attr: AttributeSyntax) -> String?
{ "name: \"\(info.name)\", type: \(info.type.longName).self" }
// AccessorMacro
public static func expansion<Ctx, Dcl>(of node: AttributeSyntax, providingAccessorsOf dcl: Dcl, in ctx: Ctx) throws -> [AccessorDeclSyntax]
where Ctx: MacroExpansionContext, Dcl: DeclSyntaxProtocol
{
let info = try getStoredPropertyInfo(from: dcl)
return [
"""
get {
let storedValue = self.value(forKey: "\(raw: info.name)")
guard let value = storedValue as? \(raw: info.type) else { fatalError("\(raw: info.name) is not of expected type ...") }
return value
}
""",
"""
set {
setValue(newValue, forKey: "\(raw: info.name)")
}
""",
]
}
}