Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-11297] Swift should not synthesize an access to "oldValue" when it is not needed #53698

Closed
layoutSubviews opened this issue Aug 13, 2019 · 2 comments
Assignees
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior.

Comments

@layoutSubviews
Copy link

Previous ID SR-11297
Radar None
Original Reporter @layoutSubviews
Type Bug
Status Resolved
Resolution Duplicate
Additional Detail from JIRA
Votes 0
Component/s
Labels Bug
Assignee @theblixguy
Priority Medium

md5: 3f22e40eb4a8f49d81a065a43dfe9a31

duplicates:

  • SR-11280 PropertyWrapper property + didSet Property Observer results in get before set failure

Issue Description:

Consider a property wrapper like so:

@propertyWrapper
struct Delayed<Value> {

    var wrappedValue: Value {
        get {
            guard let value = value else {
                preconditionFailure("Property \(String(describing: self)) has not been set yet")
            }
            return value
        }
        set {
            guard value == nil else {
                preconditionFailure("Property \(String(describing: self)) has already been set")
            }
            value = newValue
        }
    }

    private var value: Value?

}

And a use case like so:

class Foo {

    @Delayed var bar: Bar {
        didSet { print("bar has been set to \(bar)") }
    }

}

The program will crash at runtime in `Delayed.wrappedValue.get` because the synthesized setter starts by creating the implicit `oldValue` variable and accesses the wrapped value before it is initialized.

There was a short discussion on Twitter about this scenario and @jckarter suggested improving the compiler by having it not synthesizing an access to the variable if `oldValue` is never referenced in the `didSet` body.
That sounds like a great solution to this problem.

@theblixguy
Copy link
Collaborator

Duplicate of SR-11280, but PR for fix is here: #26632

@theblixguy
Copy link
Collaborator

Just an update that the proposed change is now in review: https://forums.swift.org/t/se-0268-refine-didset-semantics/

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior.
Projects
None yet
Development

No branches or pull requests

2 participants