swiftlang / swift

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

[SR-11415] Try? with nil-coalescing operator does not resolve #53816

Open idrougge opened 5 years ago

idrougge commented 5 years ago
Previous ID SR-11415
Radar None
Original Reporter @idrougge
Type Bug
Environment Xcode 10.3 (10G8), Swift 5
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 0 | |Component/s | Compiler | |Labels | Bug, LanguageFeatureRequest | |Assignee | None | |Priority | Medium | md5: de8ec3fb2fc24920ffff647e79d3f055

Issue Description:

Given a throwing function, e.g.:

    func toss() throws -> Int {
        return 123
    }

Calling it using try? and handling the resulting optional using the ?? operator will not resolve to a non-optional:

let n: Int = try? toss() ?? 999

…instead giving the error message

Value of optional type 'Int?' not unwrapped; did you mean to use 'try!' or chain with '?'?

…as well as a fixit to replace try? with try!.

In Xcode, the function name will also not be highlighted as a function name until you apply the fixit, turning "try?" into "try!".

Wrapping the call in parentheses, e.g.:

let n: Int = (try? toss()) ?? 999

…the code will highlight and compile, but the expression should be solvable without.

belkadan commented 5 years ago

This is behaving as expected, with try? having a lower precedence than ?? to be consistent with try. I admit it's not so useful in this case, though.

Any change here would have to go through the Swift Evolution Process.