텍스트적 표현을 커스터마이징하는 타입
protocol CustomStringConvertible
프로토콜 정의 없이 구조체를 출력할 경우, 기본 표현으로 출력된다.
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)"
매번 rawValue로 지저분해지는 출력부 코드를 깔끔하게 만들어볼 수 있다.
enum Script: String, CustomStringConvertible {
var description: String {
self.rawValue
}
case win = "이겼습니다!"
case lose = "졌습니다!"
case draw = "비겼습니다!"
case gameEnd = "게임 종료"
}