With Swift, the proper way to handle errors and retrieve data from methods that may throw errors is explained in the Error Handling section of the "Swift programming language".
Therefore, according to your needs, you may choose between one of the 3 following patterns to solve your problem.
1. Retrieve data and handle errors using do-catch
and try
keyword
You use a do-catch
statement to handle errors by running a block of code. If an error is thrown by the code in the do
clause, it is matched against the catch
clauses to determine which one of them can handle the error.
Usage:
let plistUrl = Bundle.main().urlForResource("Books", withExtension: "plist")!
let plistData: Data?
do {
plistData = try Data(contentsOf: plistUrl)
} catch {
print(error as NSError)
plistData = nil
}
print(plistData)
2. Retrieve data and convert errors to optional values using try?
keyword
You use try?
to handle an error by converting it to an optional value. If an error is thrown while evaluating the try?
expression, the value of the expression is nil.
Usage:
let plistUrl = Bundle.main().urlForResource("Books", withExtension: "plist")!
guard let plistData = try? Data(contentsOf: plistUrl) else {
return
}
print(plistData)
3. Retrieve data and disable error propagation using try!
keyword
Sometimes you know a throwing function or method won’t, in fact, throw an error at runtime. On those occasions, you can write try!
before the expression to disable error propagation and wrap the call in a runtime assertion that no error will be thrown. If an error actually is thrown, you’ll get a runtime error.
Usage:
let plistUrl = Bundle.main().urlForResource("Books", withExtension: "plist")!
let plistData = try! Data(contentsOf: plistUrl)
print(plistData)