SWIFT / CHAPTER 02
Decisions and iteration
BeginnerExpress boundaries and early exits clearly.
By the end of this chapter
- Trace exclusive branches
- Use half-open ranges
- Apply guard to reject invalid input
The idea
Swift conditions require Bool values rather than numeric truthiness. if/else selects alternatives, while switch can describe several cases and requires coverage of every possibility. A guard statement exits the current scope when a required condition is not met, allowing the remaining code to proceed with that condition established. Choose the structure that makes the normal path easiest to read.
A half-open range such as 0..<4 excludes the upper bound, while 1...4 includes both endpoints. For array positions, indices avoids manually inventing bounds and works for an empty array. Accumulators should start with a neutral value and be updated once for each accepted item. Test empty input and threshold boundaries separately.
func totalPositive(_ values: [Int]) -> Int {
var total = 0
for value in values {
if value > 0 { total += value }
}
return total
}
print(totalPositive([4, -1, 3, 0]))7
Only four and three contribute to the accumulator. The function returns a value that the caller can print or reuse elsewhere.
Try it yourself
Use guard to reject a negative requested count before computing a total price.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING