You use the do-catch statement to handle errors by running a block of code. If an error occurs in the code in the do clause, it maps to catch clauses to determine which one can handle the error.
Do you use try? to handle the error by converting it to an optional value. If an error was selected during the evaluation of the attempt? expression, the value of the expression is zero. For example, in the following code, x and y have the same meaning and behavior:
func someThrowingFunction() throws -> Int {
}
let myValue1 = try? someThrowingFunction()
let myValue2: Int?
do {
myValue2 = try someThrowingFunction()
} catch {
myValue2 = nil
}
If someThrowingFunction () throws an error, the value of myValue1 and myValue2 is zero. Otherwise, the value of myValue1 and myValue2 is the value returned by the function. Note that myValue1 and myValue2 are optional for any type of someThrowingFunction (). Here the function returns an integer, so myValue1 and myValue2 are optional integers.
Using try? Allows you to write compressed error handling code if you want to handle all errors the same way. For example, the following code uses several approaches to retrieve data or returns nil if all approaches fail
func fetchData() -> Data? {
if let data = try? fetchDataFromDisk() { return data }
if let data = try? fetchDataFromServer() { return data }
return nil
}
nil, : -
var myValue: Int?
if let checkValue:Int = myValue {
// run this when checkValue has a value which is not ni
}