debugging - Is there a way to use tabs to evenly space out description strings in Swift? -
overriding description variable of custom class:
override var description : string { let mirrored_object = mirror(reflecting: self) let str:nsmutablestring = nsmutablestring() (index, attr) in mirrored_object.children.enumerated() { if let property_name = attr.label string! { //str.append(" attr \(index): \(property_name) = \(attr.value)\n") str.append("\t\(property_name) = \t\t\(attr.value)\n") } } return str string }
produces output looks like:
userid = optional(0) username = optional("testuser") email = optional("test@gmail.com")
is there way set tabs in output attribute values line nicely this?
userid = optional(0) username = optional("testuser") email = optional("test@gmail.com")
also, there way rid of or shorten "optional" part , show value?
i wouldn't use tabs use padding(...)
:
var description : string { let mirrored_object = mirror(reflecting: self) let childrenwithlabel = mirrored_object.children.filter { $0.label != nil } let maxlen = childrenwithlabel.map { int($0.label!.characters.count) }.max() ?? 0 let lines = childrenwithlabel.map { $0.label!.padding(tolength: maxlen, withpad: " ", startingat: 0) + " = \($0.value)" } return lines.joined(separator: "\n") }
for struct like
struct foo: customstringconvertible { let userid = 42 let username = "foo" let verylongpropertyname: string? = "bar" }
this produces
userid = 42 username = foo verylongpropertyname = optional("bar")
as "optional" part, it's not easy totig suggests because value mirror of type any
. see this question.
update
i overlooked wanted have different format.
var description : string { let mirrored_object = mirror(reflecting: self) let childrenwithlabel = mirrored_object.children.filter { $0.label != nil } let separator = " = " let firstcolumnwidth = (childrenwithlabel.map { int($0.label!.characters.count) }.max() ?? 0) + separator.characters.count let lines = childrenwithlabel.map { ($0.label! + separator).padding(tolength: firstcolumnwidth, withpad: " ", startingat: 0) + "\($0.value)" } }
produces
userid = 42 username = foo verylongpropertyname = optional("bar")
update 2
to rid of "optional" thing, please see my answer here.
if use (from said answer) unwrap()
or unwrapusingprotocol()
in description
this:
var description : string { let mirrored_object = mirror(reflecting: self) let childrenwithlabel = mirrored_object.children.filter { $0.label != nil } let separator = " = " let firstcolumnwidth = (childrenwithlabel.map { int($0.label!.characters.count) }.max() ?? 0) + separator.characters.count let lines = childrenwithlabel.map { ($0.label! + separator).padding(tolength: firstcolumnwidth, withpad: " ", startingat: 0) + "\(unwrap($0.value))" } return lines.joined(separator: "\n") }
this produce
userid = 42 username = foo verylongpropertyname = bar
Comments
Post a Comment