1. Error Handling
在Swift中,用满足ErrorType协议类型来表示Error。
enum
VendingMachingError:
ErrorType
{
case
InvalidSelection
case
OutOfStock
}
func
canThrowErrors()
throws
->
String
func
cannotThrowErrors() ->
String
struct
Item {
var price: Double
var count: Int
}
var inventory = [
"Candy Bar" : Item (price: 1.25 ,count: 7 ),
"Chips" : 1.00 ,216)">4 ),27)">"Pretzels" : 0.75 ,216)">11 )
]
var amountDeposited = 1.00
func vend(itemNamed name: String ) throws {
guard var item = inventory [name] else {
throw
VendingMachingError . InvalidSelection
}
guard item. count > 0 throw @H_767_404@OutOfStock
}
if amountDeposited >= item. price {
amountDeposited -= item. price
--item. count
inventory [name] = item
} let amountrequired = item. price - amountDeposited
InsufficientFunds (required: amountrequired)
}
var price: Double
var count: Int
}
var inventory = [
"Candy Bar" : Item (price: 1.25 ,count: 7 ),
"Chips" : 1.00 ,216)">4 ),27)">"Pretzels" : 0.75 ,216)">11 )
]
var amountDeposited = 1.00
func vend(itemNamed name: String ) throws {
guard var item = inventory [name] else {
throw
VendingMachingError . InvalidSelection
}
guard item. count > 0 throw @H_767_404@OutOfStock
}
if amountDeposited >= item. price {
amountDeposited -= item. price
--item. count
inventory [name] = item
} let amountrequired = item. price - amountDeposited
InsufficientFunds (required: amountrequired)
}
}
let
favoriteSnacks = [
"Alice" : "Chips" ,27)">"Bob" : "Licorice" ,27)">"Eve" : "Pretzels"
]
func buyFavoriteSnacks(person: let snackName = favoriteSnacks [person] ?? "Candy Bar"
try vend (itemNamed: snackName)
}
"Alice" : "Chips" ,27)">"Bob" : "Licorice" ,27)">"Eve" : "Pretzels"
]
func buyFavoriteSnacks(person: let snackName = favoriteSnacks [person] ?? "Candy Bar"
try vend (itemNamed: snackName)
}
func
willOnlyThrowIfTrue(value:
Bool
)
throws
{
if value {
throw someError
}
do {
try willOnlyThrowIfTrue ( false )
} catch {
//Handle Error
}
}
if value {
throw someError
}
do {
try willOnlyThrowIfTrue ( false )
} catch {
//Handle Error
}
}
try
!
false
)
defer关键字内的语句直到离开当前代码块时才会被执行。这些语句让你能做一些必要的清理工作,不论当前代码块内有没有错误出现,defer内的语句都会执行。而且defer的执行顺序和它们被定义的顺序是相反的,比如第一个定义的defer会在第二个定义的defer之后执行。
func
processFile(filename:
String
)
if
exists(filename) {
let file = open(filename)
}
defer {
close (file)
}
while let line = try file.readline() {
//Work with the file.
}
//close(file) is called here,at the end of the scope.
let file = open(filename)
}
defer {
close (file)
}
while let line = try file.readline() {
//Work with the file.
}
//close(file) is called here,at the end of the scope.
}