검색결과 리스트
print에 해당되는 글 1건
- 2015.07.01 [swift2] 타입의 텍스트적인 표현 커스터마이징하기
글
[swift2] 타입의 텍스트적인 표현 커스터마이징하기
1. 값의 문자열 표현 얻기
모델 객체를 화면이나 디버깅 코드에 표시할 때, 텍스트적인 표현을 생성하면 유용할 때가 있습니다.
swift에서는 특정 타입을 string 형태로 표현하거나, 디버깅 목적으로 화면에 출력하기위해 CustomStringConvertible과
CustomDebugStringConvert 프로토콜을 따르도록 선언할수 있습니다. 이 프로토콜 중 하나를 따르는 타입을 정의하면 print,
debugPrint와 같은 출력함수와 string interpolation 이 기본객체의 description을 호출하지 않고 이 함수들을 호출할 것입니다.
다음과 같은 그룹채팅을 위한 Message 타입이 있습니다.
struct Message {
let from: String
let contents: String
let date: NSDate
}
messages = [
Message(from: "Sandy", contents: "Hey, what's going on tonight?", date: messageDates[0]),
Message(from: "Michelle", contents: "Studying for Friday's exam. You guys aren't?", date: messageDates[1]),
Message(from: "Christian", contents: "Nope. That's what tomorrow is for. Let's get food, I'm hungry!", date: messageDates[2]),
Message(from: "Michelle", contents: "Maybe. What do you want to eat?", date: messageDates[3])
] 메세지 객체중 하나를 출력하면, struct의 기본 description을 얻을 수 있습니다.
구조체의 모든 정보를 출력하는데, 채팅앱과 같이 특정한 경우의 로깅과 디버깅을 위해 보기좋게 포맷팅 되어 있지는 않습니다.
디버깅을 위해 특정타입이 출력되는방식을 커스터마이징 하기위해 CustomDebugStringConvertiable 프로토콜을 적용할 수 있습니다.
2. 디버깅 정보 출력 - CustomDebugStringConvertible 프로토콜
CustomDebugStringConvertiable 프로토콜은 한개의 필수 속성인 debugDescription를 가집니다.
이 속성에서 반환된 string은 객체의 description을 제공하기 위해 debugPrint 와 같은 함수에 의해 사용됩니다.
CustomDebugStringConvertible 프로토콜을 적용한 뒤 메시지 출력을 시도해보겠습니다.
extension Message: CustomDebugStringConvertible {
public var debugDescription: String {
return "[\(date) From: \(from)] \(contents)"
}
}
debugPrint(messages[0])
이 description은 디버깅에 적합하며, 사용자의 채팅 메시지를 보여주고자 할때, 로컬시간이 적용된 좀더 사용자 친화적인 시간을
보여주고 싶을 수 있습니다. 좀더 사용자 친화적인 버전의 description을 생성하는 CustomStringnConvertible 프로토콜을 구현할 수 있습니다.
3. 사용자 친화적인 형식으로 출력 - CustomStringConvertible 프로토콜
CustomStringCovertible description을 제공하면, string interpolation과 print 함수는 더이상 debugDescription 속성을 사용하지 않습니다.
import Foundation
let dateFormatter = NSDateFormatter()
dateFormatter.doesRelativeDateFormatting = true
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .ShortStyle
extension Message: CustomStringConvertible {
public var description: String {
return "\(contents)\n \(from) \(dateFormatter.stringFromDate(date))"
}
}
print(messages[0])4. 요약
- 디버깅 정보를 출력하기 위해서 CustomDebugStringConvertible 프로토콜을 구현합니다.
- 사용자 친화적인 정보를 출력하기 위해서 CustomStringConvertible 프로토콜을 구현합니다.
'Swift' 카테고리의 다른 글
| [swift2] Xcode7 beta3 Swift 언어 변경사항 (0) | 2015.07.11 |
|---|---|
| [swift2] Swift에서 에러 처리 (Error Handling) (0) | 2015.07.10 |
| [swift2] 타입의 텍스트적인 표현 커스터마이징하기 (0) | 2015.07.01 |
| [swift2] Xcode7 beta2 Swift 언어 변경사항 (0) | 2015.06.24 |
| [swift] 문자열 Indexing과 Slicing (0) | 2015.06.23 |
| [swift] Map, Filter, Reduce (0) | 2015.06.22 |