在 XCode 中调试时扩展数组的值

Expanding the values of an array when debugging in XCode

在 XCode 中调试时,有没有办法完全扩展集合或字典变量,以便我可以看到各个属性的值?

比如我有这个对象:

User:
name
email
phone

当应用程序 运行 时,当我有两个用户的数组被传递时,并尝试在调试器中查看它,我看到了这个:

po users
▿ 2 elements
  ▿ [0] : <User: 0x7fa3ab597fd0>
  ▿ [1] : <User: 0x7fa3ab597bb0>


po debugPrint(users)
[MyApp.User, MyApp.User]

po users[0].name
"John"

如何在不逐一挖掘的情况下查看所有属性的值?

您可以覆盖 description 属性 并提供您自己的字符串。

override var description: String {
    return String(format: "Name: %@, Email: %@, Phone: %@", name, email, phone)
    // Or simpler: return "Name: \(name), Email: \(email), Phone: \(phone)"
}

编辑:此解决方案适用于您的 class 继承自 NSObject 的情况。如果不是这种情况,请遵循 CustomStringConvertible,正如其他解决方案所建议的那样。

为您的 User 对象或值实施 CustomStringConvertible,它们将按您的需要打印。

extension User: CustomStringConvertible {
    var description: String {
        return "Name: \(name)"
    }
}

首先,尝试使用 p myArray 而不是 po myArray

如果这不起作用并且您已经在调试器中并且不想使用对象的新 description 重新编译,您可以改为这样做:

po myArray.map { "\([=13=].val1), \([=13=].val2)"}

尝试使用 dump 而不是 debugPrint

来自 Swift 标准库函数参考:

dump(_:name:indent:maxDepth:maxItems:)

Dump an object's contents using its mirror to standard output.

Declaration
func dump<T>(_ x: T, name name: String? = default, indent indent: Int = default, maxDepth maxDepth: Int = default, maxItems maxItems: Int = default) -> T

CustomDebugStringConvertable

很好,但我建议稍微改进一下:

通过实现 debugDescription:

让你的类型符合 CustomDebugStringConvertable
extension User: CustomDebugStringConvertable{
    var debugDescription: String {
        return "Name: \(name)"
    }
}

使用 debugDescription 可以让您更详细地进行调试,同时仍保留 description 用于一般用途。