本文是學習《The Swift Programming Language》整理的相關隨筆,基本的語法不作介紹天吓,主要介紹Swift中的一些特性或者與OC差異點。
系列文章:
- Swift4 基礎部分:The Basics
- Swift4 基礎部分:Basic Operators
- Swift4 基礎部分:Strings and Characters
- Swift4 基礎部分:Collection Types
- Swift4 基礎部分:Control Flow
- Swift4 基礎部分:Functions
- Swift4 基礎部分:Closures
- Swift4 基礎部分: Enumerations
- Swift4 基礎部分: Classes and Structures
- Swift4 基礎部分: Properties
- Swift4 基礎部分: Methods
- Swift4 基礎部分: Subscripts
- Swift4 基礎部分: Inheritance
- Swift4 基礎部分: Initialization
- Swift4 基礎部分: Deinitialization
- Swift4 基礎部分: Automatic Reference Counting(自動引用計數)
- Swift4 基礎部分: Optional Chaining(可選鏈)
Error handling is the process of responding to and
recovering from error conditions in your program. Swift
provides first-class support for throwing, catching,
propagating, and manipulating recoverable errors at
runtime.
- 錯誤處理是響應錯誤以及從錯誤中恢復的過程呼盆。Swift 提供了在運行時對可恢復錯誤的拋出奈惑、捕獲、傳遞和操作的最好的支持陌选。
表示與拋出錯誤(Representing and Throwing Errors)
例子:
enum VendingMachineError:Error {
case invalidSelection;
case insufficientFunds(coinsNeeded: Int);
case outOfStock;
}
拋出錯誤:
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
處理錯誤(Handling Errors)
There are four ways to handle errors in Swift. You can
propagate the error from a function to the code that calls
that function, handle the error using a do-catch
statement, handle the error as an optional value, or
assert that the error will not occur.
- Swift 中有4種處理錯誤的方式理郑。你可以把函數拋出的錯誤傳遞給調用此函數的代碼、用do-catch語句處理錯誤咨油、將錯誤作為可選類型處理您炉、或者斷言此錯誤根本不會發(fā)生。
用Throw傳遞錯誤(Propagating Errors Using Throwing Functions)
例子
enum VendingMachineError:Error {
case invalidSelection;
case insufficientFunds(coinsNeeded: Int);
case outOfStock;
}
struct Item {
var price: Int;
var count: Int;
}
class VendingMachine {
var inventory = [
"Candy Bar": Item(price: 12, count: 17),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 11)
];
var coinsDeposited = 0;
func vend(itemNamed name:String) throws{
guard let item = inventory[name] else {
throw VendingMachineError.invalidSelection;
}
guard item.count > 0 else {
throw VendingMachineError.outOfStock;
}
guard item.price <= coinsDeposited else {
throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited);
}
coinsDeposited -= item.price;
var newItem = item;
newItem.count -= 1;
inventory[name] = newItem;
print("Dispensing \(name)");
}
}
let favoriteSnacks = [
"Alice": "Chips",
"Bob": "Licorice",
"Eve": "Pretzels",
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
let snackName = favoriteSnacks[person] ?? "Candy Bar";
try vendingMachine.vend(itemNamed: snackName);
}
buyFavoriteSnack
函數中將異常拋出役电。
用Do-Catch處理錯誤(Handling Errors Using Do-Catch)
接著上述的例子:
var vendingMachine = VendingMachine();
vendingMachine.coinsDeposited = 8;
do {
try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine);
} catch VendingMachineError.invalidSelection {
print("Invalid Selection.");
} catch VendingMachineError.outOfStock {
print("Out of Stock.");
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.");
}
執(zhí)行結果:
Insufficient funds. Please insert an additional 2 coins.
將錯誤轉換成可選值(Converting Errors to Optional Values)
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.
- 可以使用
try?
將錯誤轉成可選值赚爵,如果錯誤被拋出,那么try?
執(zhí)行的表達式結果就是nil
法瑟。
例子
enum CustomError:Error {
case invalidSelection;
}
func someThrowingFunction(_ num:Int) throws -> Int {
if num < 0{
throw CustomError.invalidSelection;
}
return num;
}
let x = try? someThrowingFunction(-1);
let y: Int?;
let z = try? someThrowingFunction(1);
do {
y = try someThrowingFunction(-1);
} catch {
y = nil;
}
print(x);
print(y);
print(z);
執(zhí)行結果:
nil
nil
Optional(1)
禁止錯誤傳遞(Disabling Error Propagation)
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.
- 如果你確定某個函數不會拋出錯誤冀膝,則使用
try!
禁止錯誤傳遞。
指定清理操作(Specifying Cleanup Actions)
You use a defer statement to execute a set of statements just before code
execution leaves the current block of code.
- 可以使用
defer
語句在執(zhí)行完代碼塊中的一系列語句時做一些清理的工作霎挟。
例子
func calculateSum(_ nums:inout [Int]) -> Int{
defer {
print("defer removeAll");
nums.removeAll();
}
var result:Int = 0;
for var index in 0...nums.count - 1{
result += nums[index];
}
return result;
}
var nums:[Int] = [1,2,3,4,5,6];
print(calculateSum(&nums));
print(nums);
執(zhí)行結果
defer removeAll
21
[]