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

Jonathan Bailey jon889 at me.com
Mon Jan 25 07:01:48 CST 2016


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:
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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160125/dcee383d/attachment.html>


More information about the swift-users mailing list