컴바인 학습중 예제코드에서 꽤나 유용한 프로토콜을 접하게되었다. 바로 CustomStringConvertible 프로토콜이다. 이 프로토콜을 채택한 객체는 description 프로퍼티를 필수적으로 가지게되어 자신이 어떤객체인지 설명할 수 있게된다. 거두절미하고 상황별 예제를 통해 알아보자
1. 디버깅 및 로깅
struct NetworkRequest: CustomStringConvertible {
var url: String
var method: String
var headers: [String: String]
var description: String {
"Request to \(url) with method \(method) and headers \(headers)"
}
}
let request = NetworkRequest(url: "https://api.example.com",
method: "GET",
headers: ["Authorization": "Bearer token"])
print("Sending network request: \(request)")
// Sending network request: Request to https://api.example.com with method GET and headers ["Authorization": "Bearer token"]
2. 사용자 인터페이스 요소 표시
struct Event: CustomStringConvertible {
var title: String
var date: Date
var description: String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
return "\(title) on \(dateFormatter.string(from: date))"
}
}
let event = Event(title: "Swift Conference", date: Date())
label.text = event.description
//Swift Conference on May 13, 2024
3. API 응답 포맷팅
struct ApiResponse: CustomStringConvertible {
var status: Int
var messafe: String
var description: String {
"Response with status \(status): \(message)"
}
}
let response = ApiResponse(status: 200, message: "OK")
print("API Response: \(response)")
// API Response: Response with status 200: OK
4. 테스트 및 문서화
// Unit Test example
func testEventDescription() {
let event = Event(title: "Swift Meetup", date: Date())
XCTAssertEqual(event.description, "Swift Meetup on \(Date())")
}
// Test Passed: 'Swift Meetup on May 13, 2024' equals 'Swift Meetup on May 13, 2024'
'Flutter' 카테고리의 다른 글
| Combine | 8. Sequencing Operators (0) | 2024.05.13 |
---|---|
| Combine | 7. Scheduling Operators (0) | 2024.05.13 |
| Combine | 6. Timing Operators (0) | 2024.05.12 |
| Combine | 5. Combining Operators (0) | 2024.05.11 |
Flutter Widget의 작동원리 (0) | 2024.05.10 |