Swift: "try
, try?
, and try!"
Many developers are confused by the different flavours of the try
keyword.

Swift: "try
, try?
, and try!"
Swift defines three variations of the try
keyword.
try
try?
try!
try
You already know how to use the try
keyword. But how does it differ from try?
and try!
?
do { try <#throwing expression#>} catch <#pattern#> {
<#statements#>
}
try <#throwing expression#>
} catch <#pattern#> {
<#statements#>
}
try?
The question mark of the try?
keyword gives us a subtle hint.
If we use the try?
keyword and an error is thrown, the error is handled by turning it into an optional value.
This means that there is no need to wrap the throwing method call in a do-catch
statement.
Ex:
if let data = try? NSData(contentsOfURL: URL, options: []) {
print("Data Loaded")
} else {
print("Unable to Load Data")
}
The try?
keyword also works great with guard
statements.
func loadContentsOfFileAtURL(URL: NSURL) -> String? {
guard let data = try? NSData(contentsOfURL: URL, options: []) else {
return nil
}
return String(data: data, encoding: NSUTF8StringEncoding)
}
try!
If an error does get thrown, your application crashes as the result of a runtime error.
The use of try!
is similar to the use of implicitly unwrapped optionals. If you are absolutely certain that an optional contains a value, you can safely use an exclamation mark to force unwrap the value of the optional. But consider the exclamation mark as a warning that you are performing an operation that may cause your application to crash.