[swift-evolution] Proposal: Add implicit/default else-behaviour for the guard statement
Pierre Monod-Broca
pierremonodbroca at gmail.com
Wed Dec 16 01:36:05 CST 2015
Looking at the numbers it would make sense mostly to return from a function. And I agree with David that control flow in loops and switches should be explicit.
So maybe a function could declare a default behavior for all its `guard`
Pierre
> Le 16 déc. 2015 à 01:42, David Waite via swift-evolution <swift-evolution at swift.org> a écrit :
>
>
>>> On Dec 15, 2015, at 4:53 PM, Vester Gottfried via swift-evolution <swift-evolution at swift.org> wrote:
>> <snip>
>>
>> My proposal would be to make the else block optional and define a default behaviour.
>>
>> For example:
>>
>> func foo(x: Int) {
>> guard x < 10
>> ...
>> }
>>
>> swift would implicitly add "else { return }”
>
> That makes sense
>
>> --
>>
>> func foo(x: Int) -> Int? {
>> guard x < 10
>> …
>> }
>>
>> swift would implicitly add "else { return nil }”
> You would need to decide how this plays into the type system
> - is Optional a special case
> - or, will it work with anything NilLiteralConvertible (Optional, ImplicitlyUnwrappedOptional, Pointer types, Selectors)
>
> I thought of using the no-argument initializer, but that creates too much default behavior (empty arrays, zero doubles, etc).
>
> Plus, it is inconsistent with variable declarations, which require explicit initialization before use.
>
>> --
>>
>> for i in 0..<10 {
>> guard i%2 == 0
>> }
>> swift would implicitly add "else { continue }”
>> switch {
>> case a :
>> guard x != y
>> case b :
>> ...
>> }
>> swift would implicitly add "else { break }"
>
> -1 . Flow control functions need to be explicit, else I risk having (and assuming) the wrong behavior when I copy and paste code from one context to another.
>
> Plus, why would I expect a guard in a for loop to break or continue as a default behavior? I personally know I would constantly think this guard as ‘does what I mean’, while in the debugger it seems to be doing exactly the opposite of what I assumed, every time, regardless of my assumption ;-)
>
>>
>> func foo(x: Int) -> Int {
>> guard x < 10
>> ...
>> }
>>
>> swift would provide a warning that the guard statement needs an else block
>
> Iff your proposal was to call the no-argument initializer, this would return 0. For the other options this would need to return an error, not a warning.
>
> -DW
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151216/bd16ed1e/attachment.html>
More information about the swift-evolution
mailing list