Is there a way to use tabs to evenly space out description strings in Swift?

前端 未结 2 1575
北海茫月
北海茫月 2021-01-15 04:21

Overriding the description variable of a custom class:

override var description : String {
        let mirrored_object = Mirror(reflecting: self)
        let         


        
2条回答
  •  一生所求
    2021-01-15 04:32

    Try use this method. It first calculates the max length of the property, and then uses that to pad the property names:

    let maxPropertyLength: Int = mirrored_object.children.map { Int($0.label?.characters.count ?? 0) }.max() ?? 0
    for attr in mirrored_object.children {
        if let propertyName = attr.label {
            str.append("\(propertyName.padding(toLength: maxPropertyLength + 2, withPad: " ", startingAt: 0)) = \(attr.value)\n")
        }
    }
    return str as String
    

提交回复
热议问题