- 四種方式處理錯誤
- 繼續用throwing函數拋出錯誤(若是在一個方法內部不想處理錯誤,這時候想繼續拋出錯誤能夠用try去執行這個函數返回值類型是trows。)
- do,try,catch處理錯誤(一個函數能夠在內部處理錯誤)
- 將錯誤變爲可選類型(想把拋出的錯誤轉成可選類型,這時候用try?trowErrorMethod,它將會返回兩種類型,一種是nil就是出錯,還有一種是真正無錯的返回值類型)
- 禁止錯誤傳遞 (若是能夠確保一個方法不會拋出錯誤,那麼能夠禁止錯誤拋出try!trowErrorMethod)
enum VendingMachineError: Error {
case invalidSelection
case infufficientFounds(coinsNeeded:Int)
case outOfStock
}
struct Item {
var price: Int
var count: Int
}
class VendingMachine {
var inventory = [
"Candy Bar": Item(price: 12, count: 7),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 11)
]
var coinsDeposited = 0
func vend(name: String)throws -> Bool {
guard var item = inventory[name] else {
throw VendingMachineError.invalidSelection
}
guard coinsDeposited >= item.count else {
throw VendingMachineError.infufficientFounds(coinsNeeded: item.count - coinsDeposited)
}
guard item.count > 0 else {
throw VendingMachineError.outOfStock
}
item.count -= 1
inventory[name] = item
return true
}
}
//1. throwing函數繼續拋出錯誤
struct Purchased {
var name: String
init(name: String, machine: VendingMachine) throws{
self.name = name
try machine.vend(name: name)
}
}
//2. do,try,catch處理
do {
let a = try Purchased(name: "sts", machine: VendingMachine())
print(a)
} catch VendingMachineError.invalidSelection {
print("無效選擇")
}catch {
print(error)
}
do {
let machine = VendingMachine()
machine.coinsDeposited = 5
let a = try machine.vend(name: "Candy Bar")
print(a)
} catch VendingMachineError.invalidSelection {
print("無效選擇")
}catch {
print(error)
}
//3. 將錯誤轉成可選值
let machine = VendingMachine()
machine.coinsDeposited = 7
let ret = try? machine.vend(name: "Pretzels")
print(ret as Any)
//4. 禁用錯誤傳遞
let machine1 = VendingMachine()
machine1.coinsDeposited = 100
let ret1 = try! machine1.vend(name: "Pretzels")
print(ret1)
複製代碼
- 延時執行defer
- 延時執行代碼,在函數調用完畢後執行
- 每每作一些清理工做
//僞代碼
func dealFile(fileName: String){
if exists(fileName) {
let file = open(fileName)
defer {
close(fileName)
}
//處理文件
}
}
var a = 3
func test() -> Int {
defer {
a = 5
}
return a
}
print(test())
print(a)
//打印以下
//3
//5
複製代碼