티스토리 뷰
출처
오류 처리란 (Error Handling)
오류를 표시하고 던지기
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
오류를 처리하는 방법들
던지는 함수를 이용하여 오류 전달 (Propagating)
func canThrowErrors() throws -> String {
return "canThrow"
}
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(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)
}
struct PurchasedSnack {
let name: String
init(name: String, vendingMachine: VendingMachine) throws {
try vendingMachine.vend(itemNamed: name)
self.name = name
}
}
Do-Try-Catch 를 사용한 오류 처리
do {
try expression
statements
} catch pattern 1 {
statements
} catch pattern 2 where condition {
statements
}
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.")
}
// Prints "Insufficient funds. Please insert an additional 2 coins."
옵셔널 값으로 오류 변경하기
func fetchData() -> Data? {
if let data = try? fetchDataFromDisk() { return data }
if let data = try? fetchDataFromServer() { return data }
return nil
}
오류 전달을 사용하기 않기
let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")
정리 작업 지정 (Specifying Cleanup Actions, finally)
func processFile(filename: String) throws {
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.
}
}
enum DivideError: Error {
case ZeroDivideError(code: Int)
}
func divide(_ originalValue: Int, _ value: Int) throws -> Int {
if value == 0 {
throw DivideError.ZeroDivideError(code: 999)
}
return originalValue / value
}
for value in 0..<10 {
defer {
print("defer was called")
}
do {
try divide(100, value)
} catch {
print("error occured")
break
}
}
'iOS 개발 > Swift' 카테고리의 다른 글
[Swift 3] 중첩 타입 (Nested Types) (0) | 2017.04.21 |
---|---|
[Swift 3] 타입 변환 (Type Casting) (0) | 2017.04.20 |
[Swift 3] 옵셔널 체이닝 (Optional Chaining) (0) | 2017.04.18 |
[Swift 3] ARC (Automatic Reference Counting) (0) | 2017.04.18 |
[Swift 3] 제네릭 (Generics) (0) | 2017.04.16 |
- Total
- Today
- Yesterday
- delegate
- Swift 3.0
- 꺼내먹어요
- NSManagedObject
- Arc
- dictionary
- EffectiveObjectiveC
- CGImage
- 읽기 좋은 코드가 좋은 코드다
- RunLoop
- Block
- applicationWillResignActive
- NSManagedObjectContext
- Swift 3
- Swift
- coredata
- AWS
- CIImage
- docker
- ios
- thread
- UIView
- workerThread
- Swfit
- HTTP
- Swift3
- NSManagedObjectModel
- optional
- string
- set
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |