[swift-users] try? with a function that returns an optional

Svein Halvor Halvorsen svein.h at lvor.halvorsen.cc
Mon Jan 25 09:49:59 CST 2016


This is exactly according to the documentation.
In your first example `someThrowingFunction` returns an `Int`, so `y` is
defined as an `Int?`.
In the second example `someThrowingFunction` returns an `Int?`, so `y`
should be an `Int??`

However, since you didn't update the definition of `y` in your second
example, the if branch either assigns an `Int?` to an `Int?`, which is
legal, and may be nil, or it explicitly sets it to nil, which is also
legal. Thus, effectively unwrapping the nested optionals.

Yu could also apply a `flatMap` to the nested optional, like so:

let x = (try? someThrowingFunction())?.flatMap({$0})

I'm not sure if it's more readable, though.


2016-01-25 14:01 GMT+01:00 Jonathan Bailey via swift-users <
swift-users at swift.org>:

> In the language guide on the apple website,
> https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID542
>
> It says the following assignments to x and y are equivalent:
>
>    1. func someThrowingFunction() throws -> Int { ... }
>
>
>    1. let x = try? someThrowingFunction()
>    2. // x has type `Int?`
>    3.
>    4. let y: Int?
>    5. do {
>    6. y = try someThrowingFunction()
>    7. } catch {
>    8. y = nil
>    9. }
>
>
> However this isn’t the case if someThrowingFunction also returns an
> optional, say:
>
>
>    1. func someThrowingFunction() throws -> Int? { ... }
>
>
> The type of x would be `Int??`, but the type of y is still `Int?`, is
> there some way to make the `try?` return an `Int?` instead of a double
> optional, which is not very helpful.
>
> Thanks,
> Jonathan
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160125/2b6533e3/attachment.html>


More information about the swift-users mailing list