try? priority


(J.E. Schotsman) #1

I was surprised when I got a compiler error for this code:

if try? MyThrowingFunction() != nil {…} (MyThrowingFunction does not return an optional value)

This compiles:

if (try? MyThrowingFunction) != nil {…} (Xcode 7.3.1)

Shouldn’t try? have higher priority than != here?

Please disregard if this is changed in Swift 3

Jan E.


(Zhao Xin) #2

I encountered similar issue today too.

My code was like

if try? bookmarkPlistURL.checkResourceIsReachable() ?? false {

    ....

}

And the IDE (Xcode) wrongly suggests me to change try? to try!, which I did
and my app crashed when `throws`. The only right approach is to change code
to

if (try? bookmarkPlistURL.checkResourceIsReachable()) ?? false {

Besides, if you chose to use an indicator, Xcode would kindly tell you the
`?? false` part would never run.

let foo = try? bookmarkPlistURL.checkResourceIsReachable() ?? false // Left
side of nil coalescing operator '??' has non-optional type 'Bool', so the
right side is never used

So the behavior is on purpose? I just want to learn if anyone can tell me
why?

Zhaoxin

···

On Thu, Aug 4, 2016 at 10:38 PM, J.E. Schotsman via swift-users < swift-users@swift.org> wrote:

I was surprised when I got a compiler error for this code:

if try? MyThrowingFunction() != nil {…} (MyThrowingFunction does not
return an optional value)

This compiles:

if (try? MyThrowingFunction) != nil {…} (Xcode 7.3.1)

Shouldn’t try? have higher priority than != here?

Please disregard if this is changed in Swift 3

Jan E.
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users