[swift-evolution] Warn about unused Optional.some(())

Charlie Monroe charlie at charliemonroe.net
Tue Jan 31 00:16:58 CST 2017


> On Jan 31, 2017, at 1:03 AM, Matthew Johnson via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
> 
> Sent from my iPad
> 
>> On Jan 30, 2017, at 5:25 PM, Slava Pestov via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> 
>>> On Jan 30, 2017, at 2:58 PM, Daniel Duan via swift-evolution <swift-evolution at swift.org> wrote:
>>> 
>>> Hi all,
>>> 
>>> Right now, expressions that evaluates to Optional<()>, Optional<Optional<()>>… gets special treatment when it’s unused. For example:
>>> 
>>> func f(s: String) {}
>>> let s: String = “”
>>> s.map(f) // no warning here, even tho the resulting type is `Optional<()>` and unused.
>>> 
>>> func g() throws {}
>>> try? g() // no warnings here neither.
>>> 
>>> This is convenient, but encourages composing map/filter/reduce, etc with side-effect-ful functions, which we have found a few cases of in our production code recently. Granted, these cases could’ve been caught with more careful code reviews. But we wouldn’t have missed them if this “feature” didn’t exist.
>>> 
>>> I think we should remove the special treatment so that code in the example above would generate a warning about `()?` being unused. Users can silence it manually by assigning the result to `_`. 
>>> 
>>> OTOH, this would undermine the convenience of `try?` when the throwing function don’t return anything.
>> 
>> IMHO, using ‘try?’ to ignore an error result, instead of just turning it into an optional, is an anti-pattern, and forcing users to write ‘_ = try? foo()’ might not be so bad…
> 
> +1

Isn't this how it was in Swift 2.x and the first versions of 3.0? I believe this was changed only recently - which I personally found as good news. In some cases you simply do not care about the error result since it has no impact if the call fails and typing "_ =" seemed like boilerplate...

If I recall correctly, this was discussed here on the list and changed to the current behavior.


> 
>> 
>>> 
>>> What do y’all think?
>>> 
>>> Daniel Duan
>>> _______________________________________________
>>> swift-evolution mailing list
>>> swift-evolution at swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>> 
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list