Skip to content

Commit cbc8b44

Browse files
authored
Merge pull request #11 from p-x9/feature/omit-initial-value-when-type-is-optional
allow an initial value to be omitted when the type is Optional
2 parents 4f545b0 + ce93e2f commit cbc8b44

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

Sources/AssociatedObjectPlugin/AssociatedObjectMacro.swift

+4-3
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,9 @@ extension AssociatedObjectMacro: AccessorMacro {
8282
return []
8383
}
8484

85-
// Initial value required
86-
guard let defaultValue = binding.initializer?.value else {
85+
let defaultValue = binding.initializer?.value
86+
// Initial value required if type is optional
87+
if defaultValue == nil && !type.isOptional {
8788
context.diagnose(AssociatedObjectMacroDiagnostic.requiresInitialValue.diagnose(at: declaration))
8889
return []
8990
}
@@ -103,7 +104,7 @@ extension AssociatedObjectMacro: AccessorMacro {
103104
self,
104105
&Self.__associated_\(identifier)Key
105106
) as? \(type)
106-
?? \(defaultValue)
107+
?? \(defaultValue ?? "nil")
107108
"""
108109
}
109110
),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//
2+
// TypeSyntax+.swift
3+
//
4+
//
5+
// Created by p-x9 on 2023/06/27.
6+
//
7+
//
8+
9+
import SwiftSyntax
10+
import SwiftSyntaxBuilder
11+
12+
extension TypeSyntax {
13+
var isOptional: Bool {
14+
if let optionalType = self.as(OptionalTypeSyntax.self) {
15+
return true
16+
}
17+
if let simpleType = self.as(SimpleTypeIdentifierSyntax.self),
18+
simpleType.name.trimmed.text == "Optional" {
19+
return true
20+
}
21+
return false
22+
}
23+
}

0 commit comments

Comments
 (0)