[swift-evolution] Warn about unused Optional.some(())
Daniel Duan
daniel at duan.org
Tue Jan 31 10:16:48 CST 2017
Good to know the history. If I were to fix the inconsistency, I'd add the warning to optional chaining instead.
Deliberately make the compiler give us *less* information for esthetic reasons feels wrong to me. As I mentioned in the original email, this has cost us a few unnoticed bad patterns slipping into our production. That's the opposite of what this type of warning is supposed to achieve.
> On Jan 31, 2017, at 1:07 AM, Alex Hoppen <alex at ateamer.de> wrote:
>
> This was a deliberate change between Swift 3 beta 1 and beta 2 after a friend of mine pointed the following inconsistency out to me:
>
> struct Foo {
> func bar() {}
> }
> let foo: Foo? = Foo()
> foo?.bar() // Does not create a warning
> true ? foo?.bar() : foo?.bar() // expression of type '()?' is unused
>
> After some offline discussion at WWDC with the Swift team we decided to move to a consistent model where ()?, ()??, … is always discardable since we didn't want to take the convenience of foo?.bar() away (something that regularly occurs with weak variables, e.g. captures in closures).
>
> So much for the history of this feature.
>
> – Alex
>
>
>> On 30 Jan 2017, at 22:58, 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.
>>
>> What do y’all think?
>>
>> Daniel Duan
>> _______________________________________________
>> 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