Skip to content

Commit

Permalink
Add section about using XCTUnwrap in tests (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxswain-linkedin authored Jul 17, 2020
1 parent 5f238fd commit c15058f
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ func handleDigit(_ digit: Int) throws {
* **3.5.3** If you don't plan on actually using the value stored in an optional, but need to determine whether or not this value is `nil`, explicitly check this value against `nil` as opposed to using `if let` syntax.

```swift
// PREFERERED
// PREFERRED
if someOptional != nil {
// do something
}
Expand Down Expand Up @@ -612,6 +612,25 @@ guard let myValue = myValue else {
}
```

* **3.5.6** Use `XCTUnwrap` instead of forced unwrapping in tests.
```swift
func isEvenNumber(_ number: Int) -> Bool {
return number % 2 == 0
}

// PREFERRED
func testWithXCTUnwrap() throws {
let number: Int? = functionThatReturnsOptionalNumber()
XCTAssertTrue(isEvenNumber(try XCTUnwrap(number)))
}

// NOT PREFERRED
func testWithForcedUnwrap() {
let number: Int? = functionThatReturnsOptionalNumber()
XCTAssertTrue(isEvenNumber(number!)) // may crash the simulator
}
```

### 3.6 Protocols

When implementing protocols, there are two ways of organizing your code:
Expand Down

0 comments on commit c15058f

Please sign in to comment.