Build functions and handle optionals safely
Define reusable functions and unwrap optional values.
- Write a function and use
if letto 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.
1func double(_ value: Int) -> Int {
2 value * 2
3}
4
5if let line = readLine(), let number = Int(line) {
6 print(double(number))
7}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 letto 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.
Convert minutes to seconds
Write toSeconds(_:) that returns minutes × 60. Read one integer minute value and print the result.
- Two minutes
- Zero minutes
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…