gpt4 book ai didi

swift - 在 Swift 中访问 CustomStringConvertible 的默认实现

转载 作者:行者123 更新时间:2023-11-28 11:11:36 28 4
gpt4 key购买 nike

我想通过添加一些额外的输出来扩展我的 classCustomStringConvertible 协议(protocol)的默认行为。

例如,假设您在名为 Bar 的项目中有这个 class:

class Baz {
let x = 42
}
let b = Baz()

当执行 po(b) 时,输出将是 Bar.Baz

我想显示一些额外的东西,例如 x 的值,而不必再次键入 Bar.Baz

这可能吗?

最佳答案

您使用的大多数类都有 CustomStringConvertible 的默认实现的原因是 NSObject(所有 Obj-C 类的父类(super class))实现了它。

如果你定义了自己的Swift基类,你必须先声明它符合CustomStringConvertible,然后再实现它,例如

class Dog: CustomStringConvertible {
// some code and stuff here
var name = "Bobby"

// conform to CustomStringConvertible
var description: String {
return "\(NSStringFromClass(self.dynamicType)) \(name)"
}
}

print(Dog()) // outputs: "__lldb_expr_70.Dog Bobby" in Playground

不符合 CustomStringConvertible 的类仅打印类名。

关于swift - 在 Swift 中访问 CustomStringConvertible 的默认实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667244/

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