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-6911] Require explicit capture of reference types by closures #49460

Open
swift-ci opened this issue Feb 2, 2018 · 2 comments
Open

[SR-6911] Require explicit capture of reference types by closures #49460

swift-ci opened this issue Feb 2, 2018 · 2 comments
Labels
compiler The Swift compiler in itself feature A feature request or implementation improvement

Comments

@swift-ci
Copy link
Collaborator

swift-ci commented Feb 2, 2018

Previous ID SR-6911
Radar None
Original Reporter ibsh (JIRA User)
Type Improvement
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Improvement, LanguageFeatureRequest
Assignee None
Priority Medium

md5: c3a3d67f0204fffc29c85b9c6b9757f6

Issue Description:

My team have been discussing the idea of requiring a specific entry in a closure's capture list in order to close over any reference-typed instance. This may be considered onerous but we liked the idea for its explicit documentary nature: I present it here for comment and consideration.

For example:

func superFunc(session: AnyObject, identifier: Int) {
    preProcess(completion: {
        session.validate(self, with: identifier)
    })
}

might become

func superFunc(session: AnyObject, identifier: Int) {
    preProcess(completion: { [unowned self, weak session]
        session?.validate(self, with: identifier)
    })
}

or similar.

@belkadan
Copy link
Contributor

This would need to go through the Swift Evolution Process.

@swift-ci
Copy link
Collaborator Author

Comment by Stephane Magne (JIRA)

A slight variation on this that I think would work would be to make all references weak by default, while requiring the user to enforce a strong reference.

func superFunc(session: AnyObject, identifier: Int) {
    preProcess(completion: { [strong self] in 
        session?.validate(self, with: identifier)     
    })
} 

In this case, self is explicitly held, and another developer coming across this code can see clear intent. Further, any implicitly made weak reference, such as session in this scenario, would also have the explicit ? enforced by the compiler.

In that sense, there is a cue to reader in all cases what is happening, and helps the code become more self-documenting, and likely reducing rates of accidental retain cycles.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
compiler The Swift compiler in itself feature A feature request or implementation improvement
Projects
None yet
Development

No branches or pull requests

2 participants