[swift-evolution] Proposal: Add implicit/default else-behaviour	for the guard statement
    David Waite 
    david at alkaline-solutions.com
       
    Tue Dec 15 18:42:01 CST 2015
    
    
  
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151215/0e2414ff/attachment.html>
    
    
More information about the swift-evolution
mailing list