Write Swift programs with types, optionals and reusable functions.

Before starting: Terminal use and an installed Swift toolchain.

Practice project: Handle optional conversion results without a forced unwrap.

Foundation and first practice

  1. Unwrap a Swift optional safely

    Converting arbitrary text to an integer can fail. Swift uses an optional value to express that no result may exist. Optional binding lets the program use the integer only in the successful branch. A forced unwrap would turn a failed conversion into a runtime trap instead of a useful response.

    Swift toolchain; command-line example

    let text = "42"
    if let value = Int(text) {
        print(value + 1)
    } else {
        print("Enter a whole number")
    }
    Check the output
    43

    Test an empty string and a negative integer. Explain why the successful branch can use value without another optional unwrap.

Trace changing state and check loop boundaries

A trace table records the state after each statement. It helps distinguish an incorrect algorithm from a syntax mistake. Write the input contract first: this example accepts a list of numbers and returns their sum. The initial total is zero, so an empty list returns zero.

Paper trace first; pseudocode is not executable. Use your chosen language compiler or interpreter for the implementation.

PSEUDOCODE — translate before running
total ← 0
FOR EACH value IN values
    total ← total + value
RETURN total
Check the output
[2, -1, 4] → 5
[] → 0
[7] → 7
The loop must process each element exactly once.

Trace [-3, 3] without running code. Then implement and test it. Explain why starting at the second element loses data. Reject non-number input or explicitly document that it is outside the input contract.

Open the Swift learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.