Loading
0x50Lesson 6 of 7

Build functions and handle optionals safely

Define reusable functions and unwrap optional values.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Write a function and use if let to handle optional input.

Functions package reusable behavior. Optionals represent values that may be absent (nil). Use optional binding (if let) to safely unwrap values before using them, and avoid force unwrapping unless you are certain a value exists.

main.swift
1func double(_ value: Int) -> Int {
2    value * 2
3}
4
5if let line = readLine(), let number = Int(line) {
6    print(double(number))
7}
Output
Input: 6
12

Swift encourages explicit handling of missing values to prevent null-reference crashes. You can also use guard let for early exits when an optional is nil.

Key takeaways

  • Write a function and use if let to handle optional input.

  • Swift favors clear intent and safe defaults.

  • Compiler feedback is part of the learning loop.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Swift

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.

Exercise 1

Convert minutes to seconds

+25 XP

Write toSeconds(_:) that returns minutes × 60. Read one integer minute value and print the result.

  • Two minutes
  • Zero minutes
main.swift
Loading editor…

Swift lessons are authored for Swift 6.4; exercises run on Swift 6.0.1 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: