본 내용은 Swift 공식 문서에 기반하여 작성되었습니다.
https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html
Error Handling
프로그램 실행 시 혹시나 발생할 수 있는 에러에 대한 처리
func canThrowAnError() throws {
// this fuction may or may not throw an error
}
// 이 함수는 아래와 같이 do-try-catch 를 통해 사용하면 특정 Error에 대해 처리할 수 있다.
do {
try canThrowAnError()
// no error was thrown
} catch {
// an error was thrown
}
[예시]
func makeASandwich() throws {
// ...
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}
// 위 예시 코드를 보면, makeASandwich 코드는 깨끗한 접시가 없는 경우(첫 번째 catch)와 재료가 부족한 경우에 Error를 발생시킨다. 만약 에러가 없을 경우 makeASandwich 이후에 eatASandwich 한다.
Assertions and Preconditions
이후의 코드를 실행하기 이전에 특정 필수 조건이 반드시 만족되는지를 확인하기 위해 사용
[Assert]
let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 isn't >= 0.
// 위 예시 코드의 경우 age가 0보다 작으므로 (크거나 같지 않으므로) 우측의 스트링을 제공하고 앱이 꺼지므로, 에러가 발생한 위치를 정확하게 파악하는 용도로 편리하다. 또한 디버깅 시에만 작동한다.
// 만약 조건을 이전 코드에서 체크한 경우, assertionFailure를 사용한다.
if age > 10 {
print("You can ride the roller-coaster or the ferris wheel.")
} else if age >= 0 {
print("You can ride the ferris wheel.")
} else {
assertionFailure("A person's age can't be less than zero.")
// 조건 없이 Failure String만 있다.
}
Enforcing Preconditions
어떤 조건이 false에 대한 가능성이 있지만, 프로그램에서는 반드시 true여야 하는 경우 사용
// In the implementation of a subscript...
precondition(index > 0, "Index must be greater than zero.")
// precondition의 경우 디버깅, 스테이징 전부 작동한다.
'DEVELOPMENT > iOS AOS' 카테고리의 다른 글
[Swift] 공식 문서 요약 - The Basics_03 (0) | 2023.09.13 |
---|---|
[Swift] 공식 문서 요약 - The Basics_02 (0) | 2023.09.13 |
[Swift] 공식 문서 요약 - The Basics_01 (0) | 2023.09.13 |