Try? helps you run code that might fail and gives you a simple yes or no answer without crashing.
Try? for optional result in 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.
let number = try? (JSONSerialization.jsonObject(with: "123".data(using: .utf8)!) as? Int)
let fileContent = try? String(contentsOfFile: "file.txt")
func canThrow() throws -> String { if Bool.random() { return "Success" } else { throw NSError(domain: "", code: 1) } } let result = try? canThrow()
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.
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)
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.
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.