[내일배움캠프 3주차 (01/14)]

yeseul jang·2026년 1월 14일

내일배움캠프

목록 보기
3/32

🔍 Memory Graph Debugger

🔍 CustomStringConvertible

📌 정의

Swift 표준 라이브러리의 프로토콜로, “이 타입을 문자열로 표현할 방법을 직접 정의하겠다” 라는 약속

protocol CustomStringConvertible {
    var description: String { get }
}
  • description이라는 연산 프로퍼티를 구현해야 함
  • print(), String(describing:) 에서 사용됨

📌 예제

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:) 을 거친다.

  • 변환순서
    1️⃣ CustomStringConvertible 채택 여부 확인
    2️⃣ 있으면 → description 사용
    3️⃣ 없으면 → 기본 구현 (타입명 + 값)

📌 활용

enum에 연관값이 있을 때

  • enum의 case를 사람이 읽기 좋은 문자열로 바꿔줌
  • 디버깅 로그, 콘솔 출력, 테스트 로그에서 유용
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)

Error와 사용

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와는 다르게 개발자를 위한 설명을 위해 쓰임.
profile
iOS 개발

0개의 댓글