try! to force unwrap a throwing function. What will it print?enum FileError: Error { case fileNotFound } func readFile(_ name: String) throws -> String { if name == "exists.txt" { return "File content" } else { throw FileError.fileNotFound } } let content = try! readFile("exists.txt") print(content)
The function readFile returns "File content" for "exists.txt" and throws an error otherwise. Using try! means the program expects no error. Since the file exists, it prints the content.
enum ParseError: Error { case invalidFormat } func parseNumber(_ str: String) throws -> Int { guard let num = Int(str) else { throw ParseError.invalidFormat } return num } let number = try! parseNumber("abc") print(number)
The string "abc" cannot be converted to an Int, so parseNumber throws invalidFormat. Using try! causes a runtime crash when an error is thrown.
try! in Swift?try! forces the program to assume no error will occur. If an error does happen, the program crashes immediately. It does not catch or handle errors.
enum NetworkError: Error { case disconnected } func fetchData() throws -> String { throw NetworkError.disconnected } var result = "" do { result = try fetchData() } catch { result = "Error caught" } print(try! fetchData())
The do-catch block catches the error and sets result to "Error caught" but does not print it. The print(try! fetchData()) line forces a crash because fetchData() throws and try! does not handle errors.
enum DataError: Error { case missingData } func loadData(_ key: String) throws -> String { if key == "valid" { return "Data loaded" } else { throw DataError.missingData } } let a = try! loadData("valid") let b = try! loadData("invalid") print(a) print(b)
The call loadData("invalid") throws missingData. Using try! on this line causes a runtime crash. The other lines run fine.