Skip to content

Commit 77f9f7a

Browse files
committed
Fix @Attribute type inference for optional properties
1 parent 9f1f6ee commit 77f9f7a

2 files changed

Lines changed: 33 additions & 32 deletions

File tree

Sources/CoreModelMacros/Attribute.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,22 @@ public struct AttributeMacro: PeerMacro {
2121
return []
2222
}
2323
}
24+
25+
internal func inferAttributeType(from type: String) -> String? {
26+
switch type {
27+
case "String": return ".string"
28+
case "Data": return ".data"
29+
case "Bool": return ".bool"
30+
case "Int16": return ".int16"
31+
case "Int32": return ".int32"
32+
case "Int64": return ".int64"
33+
case "Int": return ".int64"
34+
case "Float": return ".float"
35+
case "Double": return ".double"
36+
case "Date": return ".date"
37+
case "UUID": return ".uuid"
38+
case "URL": return ".url"
39+
case "Decimal": return ".decimal"
40+
default: return nil
41+
}
42+
}

Sources/CoreModelMacros/Entity.swift

Lines changed: 14 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -106,41 +106,23 @@ extension EntityMacro {
106106

107107
let attributes = varDecl.attributes
108108

109-
let typeName = typeSyntax.description.trimmingCharacters(in: .whitespacesAndNewlines)
109+
let rawTypeName = typeSyntax.description.trimmingCharacters(in: .whitespacesAndNewlines)
110110

111-
let inferredType: String?
112-
113-
switch typeName {
114-
case "String":
115-
inferredType = ".string"
116-
case "Data":
117-
inferredType = ".data"
118-
case "Bool":
119-
inferredType = ".bool"
120-
case "Int16":
121-
inferredType = ".int16"
122-
case "Int32":
123-
inferredType = ".int32"
124-
case "Int64":
125-
inferredType = ".int64"
126-
case "Int":
127-
inferredType = ".int64"
128-
case "Float":
129-
inferredType = ".float"
130-
case "Double":
131-
inferredType = ".double"
132-
case "Date":
133-
inferredType = ".date"
134-
case "UUID":
135-
inferredType = ".uuid"
136-
case "URL":
137-
inferredType = ".url"
138-
case "Decimal":
139-
inferredType = ".decimal"
140-
default:
141-
inferredType = nil
111+
// Strip Optional
112+
let typeName: String
113+
if rawTypeName.hasPrefix("Optional<") {
114+
typeName = rawTypeName
115+
.replacingOccurrences(of: "Optional<", with: "")
116+
.dropLast()
117+
.trimmingCharacters(in: .whitespacesAndNewlines)
118+
} else if rawTypeName.hasSuffix("?") {
119+
typeName = String(rawTypeName.dropLast()).trimmingCharacters(in: .whitespacesAndNewlines)
120+
} else {
121+
typeName = rawTypeName
142122
}
143123

124+
let inferredType = inferAttributeType(from: typeName)
125+
144126
for attr in attributes.compactMap({ $0.as(AttributeSyntax.self) }) {
145127
if attr.attributeName.description == "Attribute" {
146128
let type: String

0 commit comments

Comments
 (0)