Swift 표준 라이브러리의 프로토콜로, “이 타입을 문자열로 표현할 방법을 직접 정의하겠다” 라는 약속
protocol CustomStringConvertible {
var description: String { get }
}
enum Direction: CustomStringConvertible {
case north
case south
var description: String {
switch self {
case .north: return "⬆️ 북쪽"
case .south: return "⬇️ 남쪽"
}
}
}
let dir = Direction.north
print(dir)
// ⬆️ 북쪽
print(x) 는 그냥 출력하는 게 아니라 내부에서 문자열로 변환을 먼저 한다.
그래서 항상 String(describing:) 을 거친다.
enum NetworkState: CustomStringConvertible {
case success(code: Int)
case failure(reason: String)
var description: String {
switch self {
case .success(let code):
return "✅ 성공 (code: \(code))"
case .failure(let reason):
return "❌ 실패 (이유: \(reason))"
}
}
}
print(NetworkState.success(code: 200)) // ✅ 성공 (code: 200)
print(NetworkState.failure(reason: "Timeout")) // ❌ 실패 (이유: Timeout)
enum LoginError: Error, CustomStringConvertible {
case invalidPassword
case userNotFound
var description: String {
switch self {
case .invalidPassword:
return "비밀번호가 올바르지 않습니다."
case .userNotFound:
return "사용자를 찾을 수 없습니다."
}
}
}
func login(password: String) throws {
if password != "1234" {
throw LoginError.invalidPassword
}
}
do {
try login(password: "0000")
} catch {
print(error) // 비밀번호가 올바르지 않습니다.
}
LocalizedError와는 다르게 개발자를 위한 설명을 위해 쓰임.