8000 Added section about early exits · linuxul/swift-style-guide@fbbc088 · GitHub
[go: up one dir, main page]

Skip to content

Commit fbbc088

Browse files
committed
Added section about early exits
1 parent b71dd2b commit fbbc088

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,29 @@ It becomes easier to reason about code. Had you used `var` while still making th
3434

3535
Accordingly, whenever you see a `var` identifier being used, assume that it will change and ask yourself why.
3636

37+
### Return and break early
38+
39+
When you have to meet certain criteria to continue execution, try to exit early. So, instead of this:
40+
41+
```swift
42+
if n.isNumber {
43+
// Use n here
44+
} else {
45+
return
46+
}
47+
```
48+
49+
use this:
50+
```swift
51+
guard n.isNumber else {
52+
return
53+
}
54+
// Use n here
55+
```
56+
57+
You can also do it with `if` statement, but using `guard` is prefered, because `guard` statement without `return`, `break` or `continue` produces a compile-time error, so exit is guaranteed.
58+
59+
3760
#### Avoid Using Force-Unwrapping of Optionals
3861

3962
If you have an identifier `foo` of type `FooType?` or `FooType!`, don't force-unwrap it to get to the underlying value (`foo!`) if possible.

0 commit comments

Comments
 (0)
0