๐ŸŽ“ A1Learner
๐Ÿ”

Swift Throwing Functions

A throwing function is a function that can fail by throwing an error instead of returning a value. The throws mark in its header warns callers that failure is possible.

An error list

The LoginError enum conforms to Error and lists two ways a login check can fail. The test confirms which case a value holds.

enum LoginError: Error {
    case emptyName
    case shortPassword
}
let problem = LoginError.emptyName
print(problem == LoginError.emptyName)

A call that succeeds

The welcome function throws only for an empty name, and Ana is a fine name here. The do block prints the returned greeting.

enum LoginError: Error {
    case emptyName
}
func welcome(name: String) throws -> String {
    if name.isEmpty {
        throw LoginError.emptyName
    }
    return "Welcome, \(name)"
}
do {
    let message = try welcome(name: "Ana")
    print(message)
} catch {
    print("Login failed")
}

A call that throws

The empty name makes welcome throw before any return, so the greeting print never runs. The catch block prints its fixed line instead.

enum LoginError: Error {
    case emptyName
}
func welcome(name: String) throws -> String {
    if name.isEmpty {
        throw LoginError.emptyName
    }
    return "Welcome, \(name)"
}
do {
    let message = try welcome(name: "")
    print(message)
} catch {
    print("Login failed")
}

Example

enum VendingError: Error {
    case outOfStock
}
func buy(stock: Int) throws -> String {
    if stock == 0 {
        throw VendingError.outOfStock
    }
    return "Dispensed"
}
do {
    let first = try buy(stock: 2)
    print(first)
    let second = try buy(stock: 0)
    print(second)
} catch {
    print("Could not buy")
}

Key points

  • An enum that conforms to Error lists what can go wrong.
  • The throws mark in a function header says the function can throw an error.
  • The throw word stops the function at once and sends the error to the caller.
  • A call to a throwing function takes the try mark.
  • That call sits inside a do block, which gives the call a catch block.
  • The catch block runs only when the call throws.
  • A call that does not throw gives its return value as usual.

In this example, the buy function throws the outOfStock error when the stock is 0 and returns a word the rest of the time. The first call inside the do block has stock 2, so it prints Dispensed. The second call has stock 0 and throws, so the catch block prints its one fixed line Could not buy.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

What does the throw word do inside a function?