0
0
Swiftprogramming~5 mins

Try? for optional result in Swift

Choose your learning style9 modes available
Introduction

Try? helps you run code that might fail and gives you a simple yes or no answer without crashing.

When you want to try reading a file but it's okay if the file is missing.
When you want to convert a string to a number but the string might not be a number.
When you call a function that can throw an error but you want to handle failure quietly.
When you want to try parsing data but don't want to write full error handling.
When you want to keep your code simple and just check if something worked or not.
Syntax
Swift
let result = try? someThrowingFunction()

try? runs a function that can throw an error and returns an optional value.

If the function works, you get the value wrapped in an optional. If it fails, you get nil.

Examples
Try to convert a string to an integer. If it fails, number is nil.
Swift
let number = try? (JSONSerialization.jsonObject(with: "123".data(using: .utf8)!) as? Int)
Try to read a file. If the file is missing or unreadable, fileContent is nil.
Swift
let fileContent = try? String(contentsOfFile: "file.txt")
Try calling a function that might throw. If it throws, result is nil.
Swift
func canThrow() throws -> String {
    if Bool.random() { return "Success" } else { throw NSError(domain: "", code: 1) }
}

let result = try? canThrow()
Sample Program

This program tries to convert two strings to numbers using a throwing function. Using try? it gets optional results. The first string is a number, so it succeeds. The second is not, so it returns nil.

Swift
import Foundation

func readNumber(from text: String) throws -> Int {
    guard let number = Int(text) else {
        throw NSError(domain: "InvalidNumber", code: 1)
    }
    return number
}

let input1 = "42"
let input2 = "hello"

let number1 = try? readNumber(from: input1)
let number2 = try? readNumber(from: input2)

print("number1:", number1 as Any)
print("number2:", number2 as Any)
OutputSuccess
Important Notes

try? is a quick way to handle errors by turning them into optional values.

If you want to know why it failed, try? won't tell you. For that, use do-catch.

Use try? when failure is normal and you just want to check if it worked.

Summary

try? runs a throwing function and returns an optional result.

If the function throws an error, try? returns nil instead of crashing.

It helps keep code simple when you don't need detailed error info.