我正在尝试漂亮地打印(带有子对象的缩进)一个复合对象结构,其中父对象和每个子对象都确认 CustomDebugStringConvertible 协议。
到目前为止我的代码是:import Foundation
class StringUtils {
static func appendIfValuePresent(key: String, value: AnyHashable?, toArray array: inout [String], separator: String = ": ") {
if let value = value {
array.append("\(key)\(separator)\(value)")
}
}
}
class Address: CustomDebugStringConvertible {
var city: String? = "B'lore"
var country: String? = "India"
var pincode: String? = nil
var debugDescription: String {
var components = [String]()
StringUtils.appendIfValuePresent(key: "city", value: city, toArray: &components)
StringUtils.appendIfValuePresent(key: "country", value: country, toArray: &components)
StringUtils.appendIfValuePresent(key: "pincode", value: pincode, toArray: &components)
let debugStr = components.joined(separator: "\n")
return debugStr
}
}
class Contact: CustomDebugStringConvertible {
var phNum: String? = "111-222-33"
var email: String? = "ron@example.com"
var address: Address? = Address()
var debugDescription: String {
var components = [String]()
StringUtils.appendIfValuePresent(key: "phNum", value: phNum, toArray: &components)
StringUtils.appendIfValuePresent(key: "email", value: email, toArray: &components)
StringUtils.appendIfValuePresent(key: "address", value: address?.debugDescription, toArray: &components, separator: ":\n")
let debugStr = components.joined(separator: "\n")
return debugStr
}
}
class Student: CustomDebugStringConvertible {
var name = "ron"
var contact: Contact? = Contact()
var debugDescription: String {
var components = [String]()
StringUtils.appendIfValuePresent(key: "name", value: name, toArray: &components)
StringUtils.appendIfValuePresent(key: "contact", value: contact?.debugDescription, toArray: &components, separator: ":\n")
let debugStr = components.joined(separator: "\n")
return debugStr
}
}
let student = Student()
print(student)
上述代码片段的输出是:
// Actual output
/*
name: ron
contact:
phNum: 111-222-33
email: ron@example.com
address:
city: B'lore
country: India
*/
但是,我想这样打印:
// Expected output
/*
name: ron
contact:
phNum: 111-222-33
email: ron@example.com
address:
city: B'lore
country: India
*/
实现这一点的最佳方法是什么,保留代码的通用结构?