You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+29-4Lines changed: 29 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -28,12 +28,35 @@ Use `let foo = …` over `var foo = …` wherever possible (and when in doubt).
28
28
29
29
_Rationale:_ The intent and meaning of both keywords is clear, but *let-by-default* results in safer and clearer code.
30
30
31
-
A `let`-binding guarantees and *clearly signals to the programmer* that its value is supposed to and will never change. Subsequent code can thus make stronger assumptions about its usage.
31
+
A `let`-binding guarantees and *clearly signals to the programmer* that its value will never change. Subsequent code can thus make stronger assumptions about its usage.
32
32
33
33
It becomes easier to reason about code. Had you used `var` while still making the assumption that the value never changed, you would have to manually check that.
34
34
35
35
Accordingly, whenever you see a `var` identifier being used, assume that it will change and ask yourself why.
36
36
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
+
37
60
#### Avoid Using Force-Unwrapping of Optionals
38
61
39
62
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.
@@ -59,7 +82,7 @@ _Rationale:_ Explicit `if let`-binding of optionals results in safer code. Force
59
82
60
83
#### Avoid Using Implicitly Unwrapped Optionals
61
84
62
-
Where possible, use `let foo: FooType?` instead of `let foo: FooType!` if foo may be nil (Note that in general, `?` can be used instead of `!`).
85
+
Where possible, use `let foo: FooType?` instead of `let foo: FooType!` if `foo` may be nil (Note that in general, `?` can be used instead of `!`).
63
86
64
87
_Rationale:_ Explicit optionals result in safer code. Implicitly unwrapped optionals have the potential of crashing at runtime.
0 commit comments