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

Marco Masser lists at duckcode.com
Mon Jan 25 10:16:54 CST 2016

If your function returns an Int? then there’s a reason for that and nil will mean something. And if your function can throw or return an Int? there will also be a very good reason for that and nil will also meaning something. If you then choose to use try? Swift has to return a double Optional because otherwise it would hide information from you. The outer Optional tells you whether there was an error and the inner Optional represents the return value of the function.

But to answer your question: If I’m not mistaken, there is no way to make try? unwrap the optional result of a function in case of success.

Is the function you’re calling one that you wrote? If so, I would try to find a way to make it return a non-optional Int. Maybe the case where it would return nil could be modeled as throwing an error?



> On 2016-01-25, at 14:01, Jonathan Bailey via swift-users <swift-users at swift.org> wrote:
> 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 <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:
> func someThrowingFunction() throws -> Int { ... }
> let x = try? someThrowingFunction()
> // x has type `Int?`
> let y: Int?
> do {
>     y = try someThrowingFunction()
> } catch {
>     y = nil
> }
> However this isn’t the case if someThrowingFunction also returns an optional, say:
> 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/55098964/attachment.html>

More information about the swift-users mailing list