iOS 응용 (swift)
[iOS - swift] String(describing:), CustomStringConvertible
jake-kim
2021. 6. 3. 02:47
String(describing:)
- 모든 Type의 instance를 문자열로 변환
print(String(describing: ViewController.self)) // ViewController
- 주의: ClassName.Type할 경우 컴파일 에러 -> 특정 클래스의 타입을 얻고 싶은 경우 ClassName.self로 접근

CustomStringConvertible

- description에 대한 정의가 되어있는 프로토콜
- 스위프트의 print()와 String(decription:)은 위 description 프로퍼티를 사용
- CustomStringConvertible을 conform하고 있는 클래스의 객체를 print()하면 구현된 description프로퍼티를 사용
Linked List에서 연결된 Node 출력
- CustomStringConvertible 사용
// Linked list 모델
public class Node<T> {
public var value: T
public var next: Node?
public init(value: T, next: Node? = nil) {
self.value = value
self.next = next
}
}
// CustomStringConvertible 구현
extension Node: CustomStringConvertible {
public var description: String {
guard let next = next else {
return "\(value)"
}
return "\(value) => " + String(describing: next) + " "
}
}
- 사용
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let node1 = Node<Int>(value: 0)
let node2 = Node<Int>(value: 1)
let node3 = Node<Int>(value: 2)
node1.next = node2
node2.next = node3
print(node1.description) // 0 => 1 => 2
}
}