Swift 2: an easier way to extract values from Optionals by turning nils into thrown errors
| Originator: | radexpl | ||
| Number: | rdar://21371831 | Date Originated: | 13-Jun-2015 03:22 PM |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode 7 beta 1 (7A120f) |
| Classification: | Enhancement | Reproducible: | Always |
Here’s a common scenario:
- you do some fallible operation (that might return nil). For example, you take an untyped JSON dictionary, take elements from it, cast types, etc.
- If it’s .Some, you want to continue with some further operations, or perhaps just return the value
- if it’s nil, you want to be more specific and throw an error to report what caused the issue.
Right now, this requires something like:
guard let x = … else { throw Error }
But it would often be more convenient to turn the nil into an error inline, just like you can coalesce nils into concrete values using ??.
Here’s a nice option:
let x = try something_that_can_be_nil ?! Error
Proof of concept: https://twitter.com/radexp/status/608755467377078274
An example: https://gist.github.com/rnapier/dbffbf54274a880a6ac7
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!