swift 3 : error handling
TRANSCRIPT
![Page 1: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/1.jpg)
Swift 3 : Error Handling
군산대학교 컴퓨터정보통신공학부 컴퓨터정보공학전공
남 광 우
Swift 3 Tour and Language Guide by Apple꼼꼼한 재은씨의 Swift 2 프로그래밍
![Page 2: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/2.jpg)
Guard• 정의
• 하나 또는 그 이상의 조건을 만족하지 않으면 프로그램 콘트롤을 전이(transfer) 시켜주기 위해 사용• else 구문 필수• return 없는 function 또는 return, break, continue, throw를 이
용해 현재 컨트롤을 외부로 전이시킴
• 보통 program 파라미터의 선제조건 체크 등에 사용• Early Exit
• 예 :
guard param.length > 0 else { return false }
if 문과의 차이????
![Page 3: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/3.jpg)
func someFuncWithFirst( first: Int?, second: String?, third: Bool?) -> Bool {
guard let firstValue = first, secondValue = second, thridValue = thrid else {
return false}
// Some Operationlet someValue: Int = firstValue + secondValue + thirdValue...return true
}
Guard• Guard의 예
![Page 4: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/4.jpg)
func fetchListOfCustomers(customers: [Customer]?) throws {guard reachable else { throw APIError.APIErrorUnreachable }guard connected else { throw APIError.APIErrorNotConnected }guard let customers = customers where customers.count > 0
else { throw APIError.APIErrorNoCustomers }}
Guard• Assertion과 유사,
• 그러나 Assertion은 바로 Error 처리
• Guard는 throw 등 다양한 Error 처리에 유연
let age = -3assert(age >= 0, "A person's age cannot be less than zero")
func checkNumGuard(X:Int?) {guard let X = X where X != 10 else {
print("Error: X is 10!")return
}
![Page 5: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/5.jpg)
Guard• Where 구문을 이용한 확장
• first가 nil이 아니면서 0이 아닐 경우 실행
func someFuncWithFirst(first: Int?, second: String?, third: Bool?) -> Bool {guard let firstValue = first where first != nil else {
return false}
...return true
}
func someFuncWithFirst(first: Int?, second: String?, third: Bool?) -> Bool {guard let firstValue = first where first != nil && first != 0 else {
return false}
...return true
}
![Page 6: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/6.jpg)
Error Handling• 예상치 못한 상황
• 파일이 없는 경우• 서버가 다운되는 경우• 장치를 사용할 수 없는 경우• …
• Java에서 try/catch block
![Page 7: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/7.jpg)
Error Handling• 정의
• 프로그램에서 에러 상태로 부터 회복하고, 반응(responding)하기 위한 프로세스
• Runtime 중에 회복가능한 에러들을• 잡고(catching)• 다루고(manipulating)• 전파하고(propagating)• 던지고(throwing)
float divide( float a, float b){
float r = 0.0;
r = a/b;
return r;}
input
output
만약 0으로 나눈다면?
Throwing error
do{
Error Handling
} catch
do{
Error Handling
} catch
![Page 8: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/8.jpg)
Error 타입
enum VendingMachineError: Error {case invalidSelectioncase insufficientFunds(coinsNeeded: Int)case outOfStock
}
• Error의 표현• 열거형을 이용하여 정의됨• Error 타입 정의의 예
• Throw의 예
• Throw 함수 : 선언에 throws 명시
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
func canThrowErrors() throws -> String
![Page 9: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/9.jpg)
Error Handling의 예 : 벤딩머신
enum VendingMachineError: Error {case invalidSelectioncase insufficientFunds(coinsNeeded: Int)case outOfStock
}
Error의 정의
struct Item {var price: Intvar count: Int
}
Item Stock
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 = itemnewItem.count -= 1inventory[name] = newItem
print("Dispensing \(name)")}
}
VendingMachine
![Page 10: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/10.jpg)
Error Handling의 예 : 벤딩머신
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()
struct PurchasedSnack {let name: Stringinit(name: String, vendingMachine: VendingMachine) throws {
try vendingMachine.vend(itemNamed: name)self.name = name
}}
PurchasedSnack
?? 의미:Null이면 b
a != nil ? a! : b
![Page 11: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/11.jpg)
Do-Catch• Do~ Catch 구문
• Java에서 try/catch 구문
![Page 12: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/12.jpg)
Do-Catch• 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.")
}
![Page 13: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/13.jpg)
Error를 Optional로
• try를 ?로 구현
• 동일한 의미를 do/catch로
func someThrowingFunction() throws -> Int {// ...
}
let x = try? someThrowingFunction()
let y: Int?
do {y = try someThrowingFunction()
} catch {y = nil
}
![Page 14: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/14.jpg)
Error를 Optional로
• try를 ?로 구현의 예
func fetchData() -> Data? {
if let data = try? fetchDataFromDisk() { return data }if let data = try? fetchDataFromServer() { return data }return nil
}
![Page 15: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/15.jpg)
defer : 처리의 연기
• 정의• 특정 명령의 처리를 연기시키는 키워드
• 예 :
file open
file close
file close를 깜박한다면?{구현, 구현, 구현
}
함수 앞부분
함수 뒷부분
![Page 16: Swift 3 : error handling](https://reader036.vdocuments.pub/reader036/viewer/2022081818/5878bbb21a28ab724c8b787b/html5/thumbnails/16.jpg)
defer : 처리의 연기
• 사용법• defer를 이용해 대응 statement를 연속해서 구현• defer 블럭은 함수 종료전에 자동 실행
• 예 : 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) 의 실제 실행은 이 시점에서 수행됨!}
}