Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- 스위프트
- ribs
- swift documentation
- HIG
- scrollview
- ios
- map
- 리팩토링
- Clean Code
- collectionview
- Refactoring
- combine
- swiftUI
- RxCocoa
- SWIFT
- Observable
- clean architecture
- Xcode
- Protocol
- rxswift
- 클린 코드
- 애니메이션
- uiscrollview
- uitableview
- tableView
- UICollectionView
- Human interface guide
- 리펙토링
- UITextView
- MVVM
Archives
- Today
- Total
김종권의 iOS 앱 개발 알아가기
[iOS - swift] Error, LocalizedError, localizedDescription 개념 본문
iOS 기본 (swift)
[iOS - swift] Error, LocalizedError, localizedDescription 개념
jake-kim 2022. 1. 18. 23:45LocalizedError

- 오류에 대한 발생 이유를 설명하는 오류 프로토콜
- 해당 프로토콜을 준수하고, computed property인 `public var errorDescription: String?`를 정의하면, 사용하는쪽에서 .localiedDescription사용이 가능

localizedDescription
- error의 코멘트 역할

LoclizedDescription 활용 방법
- Error를 준수하는 타입 정의
enum RegisterError: Error { case invalidEmail case invalidPhoneNumber } - 디폴트 localizedDescription는 "The Operation couldn't be completed (...)"
print(RegisterError.invalidEmail.localizedDescription) // The operation couldn’t be completed. (ExLocalizedError.RegisterError error 0.) - localizedDescription을 재정의하기 위해서, LocalizedError 준수하고 errorDescription 연산 프로퍼티 정의
extension RegisterError: LocalizedError { public var errorDescription: String? { switch self { case .invalidEmail: return NSLocalizedString("Description of invalid email address", comment: "Invalid Email") case .invalidPhoneNumber: return NSLocalizedString("Description of invalid phone number", comment: "Invalid phone number") } } } - localizedDescription 반영 완료
print(RegisterError.invalidEmail.localizedDescription) // Description of invalid email address
* 전체 코드
enum RegisterError: Error {
case invalidEmail
case invalidPhoneNumber
}
extension RegisterError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidEmail:
return NSLocalizedString("Description of invalid email address", comment: "Invalid Email")
case .invalidPhoneNumber:
return NSLocalizedString("Description of invalid phone number", comment: "Invalid phone number")
}
}
}
print(RegisterError.invalidEmail.localizedDescription)
// Description of invalid email address
cf) Alamofire의 AFError는 아래처럼 LocalizedError를 준수하여 errorDescription을 정의

'iOS 기본 (swift)' 카테고리의 다른 글
Comments