Skip to content

Commit b4d6891

Browse files
committed
[TypeChecker] InitAccessors: Synthesize default init for init accessor properties
Fixes a bug were default initializer for an init accessor property hasn't been synthesized even when the property is marked as default initializable. Resolves: rdar://113421273
1 parent 281207f commit b4d6891

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

lib/Sema/TypeCheckStorage.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -491,11 +491,16 @@ const PatternBindingEntry *PatternBindingEntryRequest::evaluate(
491491
}
492492
}
493493

494+
auto isInitAccessorProperty = [](Pattern *pattern) {
495+
auto *var = pattern->getSingleVar();
496+
return var && var->getAccessor(AccessorKind::Init);
497+
};
498+
494499
// If we have a type but no initializer, check whether the type is
495500
// default-initializable. If so, do it.
496501
if (!pbe.isInitialized() &&
497502
binding->isDefaultInitializable(entryNumber) &&
498-
pattern->hasStorage()) {
503+
(pattern->hasStorage() || isInitAccessorProperty(pattern))) {
499504
if (auto defaultInit = TypeChecker::buildDefaultInitializer(patternType)) {
500505
// If we got a default initializer, install it and re-type-check it
501506
// to make sure it is properly coerced to the pattern type.

test/decl/var/init_accessors.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,3 +620,33 @@ func test_invalid_storage_restrictions() {
620620
init() {}
621621
}
622622
}
623+
624+
do {
625+
struct Test1 {
626+
var q: String
627+
var a: Int? {
628+
init {}
629+
get { 42 }
630+
}
631+
}
632+
633+
_ = Test1(q: "some question") // Ok `a` is default initialized to `nil`
634+
_ = Test1(q: "ultimate question", a: 42)
635+
636+
struct Test2 {
637+
var q: String
638+
639+
var _a: Int?
640+
var a: Int? {
641+
@storageRestrictions(initializes: _a)
642+
init {
643+
_a = newValue
644+
}
645+
get { _a }
646+
set { _a = newValue }
647+
}
648+
}
649+
650+
_ = Test2(q: "some question") // Ok `a` is default initialized to `nil`
651+
_ = Test2(q: "ultimate question", a: 42)
652+
}

0 commit comments

Comments
 (0)