0
0
Swiftprogramming~5 mins

Try! for forced unwrap in Swift

Choose your learning style9 modes available
Introduction

Use try! when you are sure a function will not fail and want to skip error handling.

You call a function that can throw an error but you know it won't fail in this case.
You want simpler code without writing <code>do-catch</code> blocks for guaranteed success.
You are prototyping or testing and want quick results without error handling.
You want to crash the program immediately if an unexpected error happens.
Syntax
Swift
let result = try! someThrowingFunction()

try! forces the program to run the throwing function without catching errors.

If the function throws an error, the program will crash immediately.

Examples
This calls a throwing function that returns 42. Since it never throws, try! works safely.
Swift
func getNumber() throws -> Int {
    return 42
}

let number = try! getNumber()
If you use try! on a function that throws an error, the program crashes immediately.
Swift
func fail() throws -> String {
    throw NSError(domain: "Error", code: 1, userInfo: nil)
}

// let text = try! fail() // This will crash the program
Sample Program

This program calls a throwing function that returns a string. Using try! unwraps the result without error handling because we know it won't fail.

Swift
import Foundation

func readFile() throws -> String {
    return "File content"
}

let content = try! readFile()
print(content)
OutputSuccess
Important Notes

Only use try! when you are 100% sure the function won't throw an error.

If the function does throw, the app will crash immediately, so use with caution.

For safer code, prefer try? or do-catch blocks.

Summary

try! runs a throwing function and forces the result without error handling.

It crashes the program if an error occurs.

Use it only when you are sure no error will happen.