Lesson 9 of 15

Optionals

Optionals

An optional represents a value that may or may not exist. You declare it by appending ? to the type:

var name: String? = "Alice"
name = nil  // now it has no value

Nil-Coalescing Operator

Use ?? to provide a default value when an optional is nil:

let displayName = name ?? "Anonymous"

Optional Binding

Use if let to safely unwrap an optional:

if let unwrapped = name {
    print("Hello, \(unwrapped)")
} else {
    print("No name")
}

Returning Optionals

Functions can return optionals to signal possible failure:

func findFirst(_ nums: [Int], _ target: Int) -> Int? {
    for (i, n) in nums.enumerated() {
        if n == target { return i }
    }
    return nil
}

Your Task

Write a function safeDivide that takes two integers a and b, and returns a / b as an Int?. Return nil if b is zero.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.