Level: ★☆☆☆ Label: iOS Swift 5.1 Try? “Try!” “Do-catch” by Mu Lingluo Reviewed by QiShare team
Error representations and throws
In Swift, errors are represented by values of the type that conform to the Error protocol. Error is a null protocol indicating that the type can be used for Error handling.
Error handling
Error handling in Swift is similar to exception handling in other languages, using the try, catch, and throw keywords. But unlike many other languages, including Objective-C, error handling in Swift does not involve displaying stack information for function calls. So throw and return statements have similar performance.
Use throwing functions to propagate errors
Throws a function: The function declaration is marked with throws keyword. Arguments in a function declaration (…) After, use the throws keyword before the return arrow -> to indicate that this function, method, or initialization method can throw an error.
func throwError()throws -> String
func notThrowError() -> String
Copy the code
Throwing functions can propagate errors by throwing their errors into the scope in which the function is called. Note that only throwing functions can propagate errors. Errors thrown within a non-thrown function must be handled within the function. Examples of throwing functions:
enum VendingMachineError : Error {
caseInvalidGoods//! < Goods invalidcaseStockInsufficient//! < Stock shortagecase CoinInsufficient(coinNeeded:Int)
}
struct Item {
var price : Int
var count : Int
}
class VendingMachine {
var coins : Int = 0
var goods : [String : Item] = [
"Fruit orange": Item.init(price: 3, count: 2),
"Red bull": Item.init(price: 5, count: 4),
"Sprite": Item.init(price: 4, count: 6)]
func sell(itemName name : String , itemCount count : Int) throws -> Void {
guard let item = goods[name] else {
throw VendingMachineError.InvalidGoods
}
guard item.count > 0 && item.count > count else {
throw VendingMachineError.StockInsufficient
}
guard item.price * count <= coins else{ throw VendingMachineError.CoinInsufficient(coinNeeded: Item. Price * count - coins)} // Coins can be purchased at the price of item. Price * count item.count - count) } }Copy the code
Call a throw function using the try keyword to propagate an error. Throw a function to propagate an error example:
class Customer { var itemName : String var itemCount : Int var vendingMachine : VendingMachine // Call the throw function using the 'try' keyword, To spread false / / can be thrown by the initialization method init (itemName: String, itemCount: Int, vendingMachine: vendingMachine) throws {a try vendingMachine.sell(itemName: itemName, itemCount: ItemCount) self.itemName = itemName self.itemCount = itemCount self.vendingMachine = vendingMachine} throws -> Void { try vendingMachine.sell(itemName: itemName, itemCount: itemCount) } }Copy the code
usedo-catch
Handling errors
A do catch statement handles an error in the following form:
do {
try expression
statements
} catch pattern 1 {
statements
} catch pattern 2 where condition {
statements
} catch {
statements
}
Copy the code
Examples of error handling operations
class HandleError {
class func test()->Void{
let vendmachine = VendingMachine()
vendmachine.coins = 10
do {
try vendmachine.sell(itemName: "Red bull", itemCount: 5)
print("Purchase successful")
} catch VendingMachineError.InvalidGoods {
print("Purchase failed" + "Goods invalid")
} catch VendingMachineError.StockInsufficient {
print("Purchase failed" + "Out of stock")
} catch VendingMachineError.CoinInsufficient(coinNeeded: let x){
print("Purchase failed" + "Not enough money is needed." + "\(x) coins")
}catch{
print("Purchase failed")}}}Copy the code
class HandleError {
class func test()->Void{
let vendmachine = VendingMachine()
vendmachine.coins = 10
do {
try vendmachine.sell(itemName: "Red bull", itemCount: 5)
print("Purchase successful")
} catch{
print("Purchase failed")}}}Copy the code
Determine the type of error caught:
class HandleError {
class func test()->Void{
let vendmachine = VendingMachine()
vendmachine.coins = 10
do {
try vendmachine.sell(itemName: "Red bull", itemCount: 5)
print("Purchase successful")
} catch is VendingMachineError {
print("The error thrown is VendingMachineError.")
} catch {
print("The error thrown is not a VendingMachineError.")}}Copy the code
Converts errors to optional values
Use a try? Process the error by converting it to an optional value. If you’re evaluating try? If an error is thrown when expressing, the value of the expression is nil.
func someThrowingFunction() throws -> Int {
// ...
}
let x = try? someThrowingFunction()
Copy the code
A try? Writing:
let y: Int?
do {
y = try someThrowingFunction()
} catch {
y = nil
}
Copy the code
Forbid the spread of errors
Use the try! To prevent the propagation of errors, which are raised at runtime when an error is reported by the invoked throwing function.
let x = try! someThrowingFunction()
Copy the code
Specifying clean-up operations
Use the defer keyword to defer specified cleanup actions, such as closing files, cleaning up memory, and so on, when the current scope exits. Defer will allow you to execute the statements in the code block, whether they are thrown by an error or left due to statements such as return or interrupt. Deferred action statements: Consists of the defer keyword and statements to execute later. This statement cannot contain statements that control transfer, such as return and break. You can’t throw an error. Deferred action statements are executed in the opposite order to where they are written in the code, meaning that the last to be written is executed first, and so on. Deferred execution can also be used when there are no errors to deal with.
func processFile(filename: String) throws {
if exists(filename) {
let file = open(filename)
defer {
close(file)
}
while let line = try file.readline() {
}
// close(file) is called here, at the end of the scope.
}
}
Copy the code
Resources: Swift 5.1 official programming guide
To learn more about iOS and related new technologies, please follow our official account:
You can add the following xiaobian wechat, and note to join the QiShare technical exchange group, xiaobian will invite you to join the QiShare technical Exchange Group.
QiShare(Simple book) QiShare(digging gold) QiShare(Zhihu) QiShare(GitHub) QiShare(CocoaChina) QiShare(StackOverflow) QiShare(wechat public account)
IOS View and export the project run logs, the use of Flutter Platform Channel and source code analysis and development do not cut map how to do? Vector icon (iconFont) Getting started with guide DarkMode, WKWebView, Apple login must be adapted? ATaller Strange dance weekly