[Swift] CustomStringConvertible 사용법 & 예제

728x90

CustomStringConvertible 사용법 & 예제


CustomStringConvertible란?

공식문서에는 CustomStringConvertible는 텍스트적인 표현을 커스터마이즈 하는 타입이라고 적혀있다.

사용 예제

그냥 구조체를 출력하면 기본 표현으로 출력된다

struct Point {
    let x: Int
    let y: Int
}

let p = Point(x: 21, y: 30)

print(p)
//Point(x: 21, y: 30)

CustomStringConvertible 프로토콜을 정의하면, 사용자가 정의한 형태로 출력되는 것을 확인 가능

extension Point: CustomStringConvertible {
    var description: String {
        return "(\(x),\(y))"
    }
}

print(p)
//(21,30)

출처 : Apple 공식 문서
728x90

댓글

Designed by JB FACTORY