Swift: "try, try?, and try!"

Ramesh Chavan
2 min readOct 4, 2022

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ramesh Chavan
Ramesh Chavan

Written by Ramesh Chavan

Like to work on iOS, Android, UIPath and Graph DB

No responses yet

Write a response