Swift
[Swift] CustomStringConvertible > description
yevdev
2022. 3. 14. 15:44
Swift의 문자열 보간법을 공부하던 중, CustomStringConvertible 프로토콜의 description 속성에 대한 설명이 간략하게 나와있어서 정리해보았다.
1️⃣ CustomStringConvertible ?
공식문서에 따르면 문자열 보간시 사용되는 프로토콜!
이 프로토콜로 채택한 타입은 인스턴스를 문자열로 변환할 때 사용할 고유의 표현을 제공한다고 한다.
2️⃣ CustomStringConvertible의 description 속성 ?
인스턴스를 description 속성을 사용하여 문자열로 치환할 수 있다는 것 같다.
이해가 잘 되지 않으니, 공식문서의 소스코드를 살펴보자!
struct Point {
let x: Int, y: Int
}
let p = Point(x: 21, y: 30)
print(p)
// Prints "Point(x: 21, y: 30)"
구조체를 사용하여 출력하면 이와 같은 결과가 나오는 것을 확인할 수 있다.
여기서, CustomStringConvertible 프로토콜을 이용하면 아래와 같은 출력 결과를 확인할 수 있다.
extension Point: CustomStringConvertible {
var description: String {
return "(\(x), \(y))"
}
}
print(p)
// Prints "(21, 30)"
구조체 정의시 바로 description 속성을 사용할 수 있는데, 코드는 아래와 같다.
struct Point: CustomStringConvertible {
let x: Int, y: Int
var description: String {
return "(\(x), \(y))"
}
}
let p = Point(x: 21, y: 30)
let s = String(describing: p)
print(s)
// Prints "(21, 30)"
String(describing:)을 사용함으로써 모든 유형의 인스턴스를 반환할 수 있다!
Reference
Apple Developer Document