swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.57k stars 10.36k forks source link

[SR-1670] Overridden property observer recursively calls itself if property is assigned in observer #44279

Open 05109ee7-7cd9-4cd4-92d0-698e676fc6af opened 8 years ago

05109ee7-7cd9-4cd4-92d0-698e676fc6af commented 8 years ago
Previous ID SR-1670
Radar rdar://problem/20099695
Original Reporter @an0
Type Bug
Environment Swift 3 in Xcode 8.0 beta 3
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 1 | |Component/s | Compiler | |Labels | Bug | |Assignee | None | |Priority | Medium | md5: 476b00a40bdc9c4916c77c52def63f0a

Issue Description:

It is either a language bug or documentation bug.

Relevant doc from The Swift Programming Language:

“If you assign a value to a property within its own didSet observer, the new value that you assign replaces the one that was just set.”

“In the first of these two checks, the didSet observer sets currentLevel to a different value. This does not, however, cause the observer to be called again.”

class Foo {
    init() {
        i = 0
    }

    var i: Int {
        didSet {
            print("i = \(i)")
        }
    }
}

class Bar: Foo {
    override var i: Int {
        didSet {
            i = i + 1
        }
    }
}

let bar = Bar()
bar.i = 1
belkadan commented 8 years ago

Good catch. Clarification: your didSet shouldn't be called again, but the superclass's is just part of its setter.