[swift-evolution] Proposal: Add implicit/default else-behaviour for the guard statement

Vester Gottfried vester.gottfried at gmail.com
Tue Dec 15 17:53:38 CST 2015


I find myself writing the same else blocks for guard statements over and
over again, so it might be reasonable to think about a default behaviour.

In a current project I found 217 guard statements from which 183 have
repetitive else clauses

>From which:
131 end with "else { return nil }"
44 "else { return }"
6 "else { continue }"
2 "else { break }"

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 }"

--

func foo(x: Int) -> Int? {
​    ​
guard x < 10
​    ​
...
}

swift would implicitly add "else { return nil }"

--

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 }"

--

func foo(x: Int) -> Int {
​    ​
guard x < 10
​    ​
...
}

swift would provide a warning that the guard statement needs an else block

--

Possible advantages
- Less code
​ to write​

- visually cleaner
-
​ ​
In code with multiple guard statements
​ ​
you
​ ​
would not have to repeat the else block


Possible Disadvantages
- Different behaviour in different contexts (func/return, for/continue,
switch/break, …) needs to be learned and understood
- programmers might forget that guard + else {} is an option
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151216/0c940626/attachment.html>


More information about the swift-evolution mailing list