Skip to content

Commit 32430ec

Browse files
committed
[Property delegates] Support didSet/willSet.
A property with a delegate can provide didSet/willSet. Synthesize a setter that calls didSet/willSet appropriately for such properties.
1 parent 00d6964 commit 32430ec

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/Sema/CodeSynthesis.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1807,6 +1807,12 @@ static void synthesizeSetterBody(AccessorDecl *setter,
18071807
// Synthesize the setter for a property delegate.
18081808
if (auto var = dyn_cast<VarDecl>(storage)) {
18091809
if (var->hasPropertyDelegate()) {
1810+
if (var->getAccessor(AccessorKind::WillSet) ||
1811+
var->getAccessor(AccessorKind::DidSet)) {
1812+
synthesizeObservedSetterBody(setter, TargetImpl::Delegate, ctx);
1813+
return;
1814+
}
1815+
18101816
synthesizePropertyDelegateSetterBody(setter, ctx);
18111817
return;
18121818
}

test/SILGen/property_delegates.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,28 @@ struct DelegateWithAccessors {
101101
x = y
102102
}
103103
}
104+
105+
func consumeOldValue(_: Int) { }
106+
func consumeNewValue(_: Int) { }
107+
108+
struct DelegateWithDidSetWillSet {
109+
// CHECK-LABEL: sil hidden [ossa] @$s18property_delegates022DelegateWithDidSetW
110+
// CHECK: function_ref @$s18property_delegates022DelegateWithDidSetWillF0V1xSivw
111+
// CHECK: struct_element_addr {{%.*}} : $*DelegateWithDidSetWillSet, #DelegateWithDidSetWillSet.$x
112+
// CHECK-NEXT: struct_element_addr {{%.*}} : $*Wrapper<Int>, #Wrapper.value
113+
// CHECK-NEXT: assign %0 to {{%.*}} : $*Int
114+
// CHECK: function_ref @$s18property_delegates022DelegateWithDidSetWillF0V1xSivW
115+
var x: Int by Wrapper {
116+
didSet {
117+
consumeNewValue(oldValue)
118+
}
119+
120+
willSet {
121+
consumeOldValue(newValue)
122+
}
123+
}
124+
125+
mutating func test(x: Int) {
126+
self.x = x
127+
}
128+
}

0 commit comments

Comments
 (0)