Menu
Coddy logo textTech

CustomStringConvertible

Coddy Swift 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 37번째.

값을 출력하면 Swift는 기본적으로 해당 값의 타입과 속성을 표시하고, 클래스의 경우에는 타입 이름만 표시합니다. CustomStringConvertible을 준수하고 description을 제공하면 텍스트를 제어할 수 있습니다:

struct Money {
    let cents: Int
}
struct Price: CustomStringConvertible {
    let cents: Int
    var description: String { "$\(cents / 100).\(cents % 100)" }
}

print(Money(cents: 1250))
print(Price(cents: 1250))

출력:

Money(cents: 1250)
$12.50

description은 print, 문자열 보간 및 String(describing:)에서 사용되므로 하나의 속성으로 값이 표시되는 모든 위치를 제어할 수 있습니다:

struct Point: CustomStringConvertible {
    let x: Int, y: Int
    var description: String { "(\(x), \(y))" }
}

let p = Point(x: 2, y: 5)
print("start at \(p)")
print([p, Point(x: 0, y: 0)])
print(String(describing: p).count)

출력:

start at (2, 5)
[(2, 5), (0, 0)]
6

클래스가 가장 큰 혜택을 얻습니다. 그렇지 않으면 클래스 인스턴스를 출력할 때 타입 이름만 표시되기 때문입니다.

class Account {
    let owner: String
    var balance: Int
    init(owner: String, balance: Int) { self.owner = owner; self.balance = balance }
}

class NamedAccount: CustomStringConvertible {
    let owner: String
    var balance: Int
    init(owner: String, balance: Int) { self.owner = owner; self.balance = balance }
    var description: String { "\(owner): \(balance)" }
}

print(Account(owner: "Ada", balance: 5))
print(NamedAccount(owner: "Ada", balance: 5))

출력:

main.Account
Ada: 5

description을 짧고 사람들이 읽기 쉽게 유지하세요. 이는 파싱을 위한 것이 아니며 값을 변경해서도 안 됩니다:

enum Status: CustomStringConvertible {
    case active, suspended
    var description: String {
        switch self {
        case .active: return "active"
        case .suspended: return "suspended"
        }
    }
}
challenge icon

챌린지

쉬움

Fraction 구조체(분자, 분모)가 CustomStringConvertible을 따르도록 만드세요. 해당 description은 분수를 기약분수 형태로 표시합니다. 6/8은 3/4로, 4/2는 2로, 0/5는 0으로 출력되며, 음수 분수는 부호가 앞에 붙습니다(-1/2). 약분을 위한 도우미 gcd(_:_:)를 작성하세요.

제공된 코드는 분수 a/b를 한 줄에 하나씩 읽고, 각 분수를 print로 출력합니다.

코드는 Fraction.swift와 Functions.swift에 작성하세요. main.swift에는 제공된 입력/출력 코드가 들어 있으며 수정할 수 없습니다.

직접 해보기

// 제공된 입력/출력 코드: 그대로 유지하세요
var input: [String] = []
while let line = readLine() { input.append(line) }
for line in input {
    let p = line.split(separator: "/").map { Int($0)! }
    print(Fraction(numerator: p[0], denominator: p[1]))
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: Swift 플레이그라운드