6 lines
1.5 KiB
HTML
6 lines
1.5 KiB
HTML
<!doctype html><html lang="en"><meta charset="utf-8"><title>Functions and a clear policy</title><h1>Functions and a clear policy</h1><p>15-minute session: read for 3 minutes, trace for 3, experiment for 7, and complete the check for 2. Spend longer whenever you need.</p><p>A function or subroutine names a reusable calculation. Our policy accepts nonnegative total and completed counts and returns zero when completed reaches or exceeds total. Otherwise it returns their difference. Trace (4,1), (4,4), (4,5), and (0,0). Keep printing separate from calculation. Write down why negative inputs are outside this exercise’s domain, then design an explicit rejection policy before accepting external input.</p><p><code>let</code> introduces an immutable binding and <code>var</code> a mutable one. Converting text with <code>Int(raw)</code> may produce <code>nil</code>. <code>if let</code> unwraps a present value without force-unwrapping missing data.</p><pre><code class="language-swift">func remaining(_ total: Int, _ done: Int) -> Int {
|
||
return max(0, total - done)
|
||
}
|
||
|
||
print(remaining(4, 1))
|
||
</code></pre><p><strong>Expected result:</strong> <code>3</code></p><h3>Practice and evidence</h3><p>Keep three notes: your prediction, the actual result, and why they match or differ. The completion check grades understanding; the practice task builds skill.</p><p><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/">Language reference</a></p></html> |