gpt4 book ai didi

swift - 有没有办法在 Swift 中使用制表符均匀分隔描述字符串?

转载 作者:可可西里 更新时间:2023-11-01 01:22:30 25 4
gpt4 key购买 nike

覆盖自定义类的描述变量:

override var description : String {
let mirrored_object = Mirror(reflecting: self)
let str:NSMutableString = NSMutableString()
for (index, attr) in mirrored_object.children.enumerated() {
if let property_name = attr.label as String! {
//str.append(" Attr \(index): \(property_name) = \(attr.value)\n")
str.append("\t\(property_name) = \t\t\(attr.value)\n")
}
}
return str as String
}

产生如下所示的输出:

userID =        Optional(0)
username = Optional("testuser")
email = Optional("test@gmail.com")

有没有办法在输出中设置制表符,使属性值像这样很好地排列?

userID =        Optional(0)
username = Optional("testuser")
email = Optional("test@gmail.com")

还有,有没有办法去掉或缩短“可选”部分,只显示值?

最佳答案

我不会使用制表符,而是使用 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")
}

对于像这样的结构

struct Foo: CustomStringConvertible
{
let userID = 42
let username = "Foo"
let verylongpropertyname: String? = "Bar"
}

这产生

userID               = 42
username = Foo
verylongpropertyname = Optional("Bar")

至于“可选”部分,它并不像 totiG 所建议的那样简单,因为您从镜像中获取的值是 Any 类型。参见 this question .

更新

我忽略了您想要稍微不同的格式。

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)"
}
}

产生

userID =               42
username = Foo
verylongpropertyname = Optional("Bar")

更新 2

要摆脱“可选”的东西,请参阅 my answer here .

如果您在 description 中使用(来自上述答案)unwrap()unwrapUsingProtocol(),如下所示:

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")
}

这会产生

userID =               42
username = Foo
verylongpropertyname = Bar

关于swift - 有没有办法在 Swift 中使用制表符均匀分隔描述字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43271970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com