Swift 2: setter of protocol-typed variable is invoked unexpectedly
| Originator: | Vadim.Yelagin | ||
| Number: | rdar://22799785 | Date Originated: | 22 Sep 2015 |
| Status: | Duplicate of 22676810 (Open) | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode 7.0 (7A220) |
| Classification: | Swift compiler | Reproducible: | Always |
Summary:
See attached playground for minimal reproducing example.
Protocol P has a get-only variable declaration.
Another variable has type P and a set/didSet.
Whenever the variable from the protocol is accessed via the protocol-typed variable, setter and didSet for the latter variable are called.
Steps to Reproduce:
Open and run the attached playground in Xcode 7.
Notice that "didSet" is printed 42 times.
Expected Results:
didSet is expected to never be called
Actual Results:
didSet is called each time variable is accessed (42 times)
Version:
Xcode 7.0 (7A220)
OS X 10.10.5 (14F27)
Notes:
DidSet no longer gets unexpectedly called if the protocol P is restricted to AnyObject or—surprisingly—the variable "x" declaration in protocol is changed from {get} to {get set}.
I suspect that variable "x" getter is erroneously treated as a mutating function, in which case the setter invocation would be due.
Configuration:
Xcode 7 playground, iOS 9 simulator and iOS 9 devices
Attachment:
protocol P {
var x: Bool { get }
}
class A: P {
var x = true
}
var variable: P = A() {
didSet {
print("didSet")
}
}
for _ in 1...42 {
variable.x // prints "didSet"
}
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!