요번 시간에는 에러와 예외처리에 대한 것을 배워 볼 것이다.
에러 타입은 열거형(enum)이다.
import Foundation
enum FileTransferError: Error{
case noConnection
case lowBandwidth
case fileNotFound
}
에러 던지기
func transferFile() throws{
}
func transferFile() throws -> Bool{
}
func transferFile() throws{
guard connectionOK else{
throw FileTransferError.noConnection
}
guard connectionSpeed > 30 else{
throw FileTransferError.lowBandwidth
}
guard fileFound else{
throw FileTransferError.fileNotFound
}
}
func sendFile() -> String{
do{
try fileTransfer()
}catch FileTransferError.noConnection{
return "No Network Connection"
}catch FileTransferError.lowBandwidth{
return "File Transfer Speed too low"
}catch FileTransferError.fileNotFound{
return "File not Found"
}catch {
return "Unknown error"
}
return "Successful transfer"
}
여러 객체에 접근하기
do{
try filemgr.createDirectory(...)
}catch let error{
print("...")
}
에러캐칭 비활성화하기
defer 구문 사용하기
func sendFile() -> String{
defer{
removeTmpFiles()
closeConnection()
}
do{
try fileTransfer()
}catch FileTransferError.noConnection{
return "No Network Connection"
}catch FileTransferError.lowBandwidth{
return "File Transfer Speed too low"
}catch FileTransferError.fileNotFound{
return "File not Found"
}catch {
return "Unknown error"
}
return "Successful transfer"
}
요약
import Foundation
let connectionOk: Bool = true
let connectionSpeed: Double = 30.00
let fileFound: Bool = false
let fileSize: Int = 30
//Error 프로토콜을 따르는 나만의 에러 타입
enum FileTransferError: Error{
//에러가 갖게 될 상황들을 값으로 정리함
case noConnection
case lowBandwidth
case fileNotFound
case tooBigSize
}
//이 함수는 실행중에 오류가 발생할 수 있음
func transferFile() throws {
//함수 안에서는 최대한 모든 오류 상황들을 throw로 주고 받을 수 있어야 한다.
//connectionOK가 false이면 else구문 실행되고 함수 종료
guard connectionOk else{
throw FileTransferError.noConnection
}
guard connectionSpeed > 30 else{
throw FileTransferError.lowBandwidth
}
guard fileFound else{
throw FileTransferError.fileNotFound
}
guard fileSize < 20 else{
throw FileTransferError.tooBigSize
}
}
//transferFile함수를 호출하는 응용 코드
//파일 전송을 "시도"하고 결과를 문자열로 반환
func sendFile() -> String{
//오류가 발생할수 있는 함수를 사용하는 쪽에서는 모든 오류 내용에 대해 못하더라도 최대한 많이 대응 가능하도록 해줄 필요가 있따.
//try! transferFile() -> 위험한 방법
do{
try transferFile()
}catch FileTransferError.noConnection{
return "No Network Connection"
}catch FileTransferError.lowBandwidth{
return "File Transfer Speed too low"
}catch FileTransferError.fileNotFound{
return "File not Found"
}catch let error{//여기는 tooBigSize가 걸린거임
return "Unknown error: \(error)"
}
return "Successful transfer"
}
print("\(sendFile())”)
구조체와 열거형은 값타입, 클래스는 참조타입이다.
각 진수에 따라 정수를 표현하는 방법
정수와 부동소수점 변환
문자열
let hello = "Hello"
var hasPrefix: Bool = false
hasPrefix = hello.hasPrefix("He") // true
hasPrefix = hello.hasPrefix("HE") // false
집합
열거형
enum PieType{
case Apple
case Cherry
case Pecan
}
let favoritePie = PieType.Apple
let name:String
switch favoritePie{
case .Apple:
name = "Apple"
case .Cherry:
name = "Cherry"
case .Pecan:
name = "Pecan"
}
enum PieType: Int{
case Apple = 0
case Cherry
case Pecan
}
let pieRawValue = PieType.Pecan.rawValue // pieRawValue는 2를 값으로 가진 Int 타입이다
if let pieType = PieType(rawValue: pieRawValue){
//'pieType'이 유효한 값을 가지면
}
프로퍼티 관찰자
import Foundation
class StepCounter{
var totalSteps: Int = 0{
willSet(newTotalSteps){
print("About to set totalSteps to \(newTotalSteps)")
}
didSet{
if totalSteps > oldValue{
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
stepCounter.totalSteps = 360
stepCounter.totalSteps = 896
- 오브젝티브-C의 옵저버 개념과는 많이 다르다
제너릭
제너릭 함수
func swapTwoValues<T>(_ a: inout T, _ b: inout T){
샬라샬라
}