[Swift] Warn upon discarding value of try? expression
| Originator: | AustinZheng | ||
| Number: | rdar://22413645 | Date Originated: | 24-Aug-2015 07:55 PM |
| Status: | Closed | Resolved: | |
| Product: | Developer Tools | Product Version: | |
| Classification: | Enhancement | Reproducible: |
Summary: Swift's new 'try?' keyword attempts to strike a balance between code safety and programmer convenience. It can be used in multiple contexts, including (but not limited to): - A function or initializer can return a success value or throw one of several errors; try? allows us to collapse multiple errors into a generic 'error' state by returning nil instead of any of the specific errors. - A function attempts to perform a side effect and throws an error upon failure. try? allows us to call the function and ignore any errors that may occur. Knowing that these things are subjective, I would argue that the first use case tends to be safe more often than not, while the second use case tends to be more dangerous, and should be discouraged. The first use case assigns the return value, whether it be a non-nil value or nil, to a variable, where it must be further acted upon (or at least explicitly ignored); it does not discard all information about whether an error took place or not. The second use case discards all information about whether an error took place. Having made this point, I would like to suggest that the compiler warn upon calling try? without assigning the return value to a variable, in order to discourage dangerous use of try?. Users who wish to suppress the warning could assign the return value to '_' (e.g. let _ = try? voidReturnFoo()), a pattern which several of the existing warnings already use. I suggest that doing so would strike a better balance between code safety and developer convenience. There's already precedent in the compiler, for example, warnings that suggest using 'let' instead of 'var' or assigning unused immutable values to '_'. These warnings gently encourage best practices while still leaving the developer with ultimate agency over how to structure their code. Version: Xcode 7 beta 6
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!
Austin
I'm an idiot. This behavior already exists; it's suppressed for Playgrounds, which is why I didn't see it. Note to self: always test with an actual project.