본문 바로가기
IOS🍎/iOS+Swift

[Swift] CustomStringConvertible

by Jouureee 2022. 3. 7.

CustomStringConvertible

 

인스턴스를 문자열로 변환할 때 커스텀하게 변환할수 있는 프로토콜이다.

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

let p = Point(x: 21, y: 30)
print(p)
// Prints "Point(x: 21, y: 30)"

기본 Point 구조체를 출력할때 기본 출력값으로 나오지만

CustomStringConvertible 를 사용하면 아래 description을 준수해야 하며

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

print(p)
// Prints "(21, 30)"

원하는 출력값으로 변형하여 출력을 가능하게 한다. 

 

참고 :

https://developer.apple.com/documentation/swift/customstringconvertible

 

Apple Developer Documentation

 

developer.apple.com

 

댓글