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-9475] Fix it to suggest if let when writing if x != nil { something(x!) } #51937

Open
mdiep opened this issue Dec 11, 2018 · 1 comment
Open
Labels
compiler The Swift compiler in itself improvement

Comments

@mdiep
Copy link
Contributor

mdiep commented Dec 11, 2018

Previous ID SR-9475
Radar None
Original Reporter @mdiep
Type Improvement
Additional Detail from JIRA
Votes 1
Component/s Compiler
Labels Improvement
Assignee None
Priority Medium

md5: b35dbc6f299a6bbe86dc676d3754444e

Issue Description:

Given this code:

let foo: String? = nil
if foo != nil {
    print(foo!)
}

Swift should warn and provide a fix-it to suggest that you write this instead:

let foo: String? = nil
if let foo = foo {
    print(foo)
}

(This would need to not provide a fixit if the variable is used as an l-value.)

I've seen a lot of code that does the former. It tends to make code more complicated, resulting in downstream nullability checks that aren't required. The compiler should help here.

@belkadan
Copy link
Contributor

Right now our diagnostics infrastructure doesn't have a way to "scan backwards" like this—there's no state kept across expressions. That doesn't mean it's not a good idea, though, just that it wouldn't be a trivial addition to the existing logic.

@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 improvement
Projects
None yet
Development

No branches or pull requests

2 participants