Swift Optionals and Error Handling

Effectively handle optional values and manage errors in Swift using practical code examples.

Swift Optionals and Error Handling
Photo by Iewek Gnos / Unsplash

Effectively handle optional values and manage errors in Swift using practical code examples.

// Handling optional values safely
let optionalValue: Int? = 42
if let unwrappedValue = optionalValue {
    print("The value is \(unwrappedValue)")
} else {
    print("The optional is nil")
}

// Error handling with do-catch
enum CustomError: Error {
    case someError
}

func throwError() throws {
    throw CustomError.someError
}

do {
    try throwError()
} catch {
    print("An error occurred: \(error)")
}