Skip to content

Commit

Permalink
[Property delegates] Support didSet/willSet.
Browse files Browse the repository at this point in the history
A property with a delegate can provide didSet/willSet. Synthesize a setter
that calls didSet/willSet appropriately for such properties.
  • Loading branch information
DougGregor committed Mar 27, 2019
1 parent 00d6964 commit 32430ec
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/Sema/CodeSynthesis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1807,6 +1807,12 @@ static void synthesizeSetterBody(AccessorDecl *setter,
// Synthesize the setter for a property delegate.
if (auto var = dyn_cast<VarDecl>(storage)) {
if (var->hasPropertyDelegate()) {
if (var->getAccessor(AccessorKind::WillSet) ||
var->getAccessor(AccessorKind::DidSet)) {
synthesizeObservedSetterBody(setter, TargetImpl::Delegate, ctx);
return;
}

synthesizePropertyDelegateSetterBody(setter, ctx);
return;
}
Expand Down
25 changes: 25 additions & 0 deletions test/SILGen/property_delegates.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,28 @@ struct DelegateWithAccessors {
x = y
}
}

func consumeOldValue(_: Int) { }
func consumeNewValue(_: Int) { }

struct DelegateWithDidSetWillSet {
// CHECK-LABEL: sil hidden [ossa] @$s18property_delegates022DelegateWithDidSetW
// CHECK: function_ref @$s18property_delegates022DelegateWithDidSetWillF0V1xSivw
// CHECK: struct_element_addr {{%.*}} : $*DelegateWithDidSetWillSet, #DelegateWithDidSetWillSet.$x
// CHECK-NEXT: struct_element_addr {{%.*}} : $*Wrapper<Int>, #Wrapper.value
// CHECK-NEXT: assign %0 to {{%.*}} : $*Int
// CHECK: function_ref @$s18property_delegates022DelegateWithDidSetWillF0V1xSivW
var x: Int by Wrapper {
didSet {
consumeNewValue(oldValue)
}

willSet {
consumeOldValue(newValue)
}
}

mutating func test(x: Int) {
self.x = x
}
}

0 comments on commit 32430ec

Please sign in to comment.