swift - 如何在符合协议的非 RawRepresentable 枚举上实现 CustomStringConvertible?
问题描述
考虑以下代码,其中包括:
- 一个协议,
P
- 两个枚举,
E0
并且E1
符合P
- 一个函数,
f(p:)
它接受一个实例P
作为参数
import Foundation
protocol P { }
enum E0: P { case a }
enum E1: P { case b }
func f(p: P) {
print("\(type(of: p)).\(p)")
}
let e0_a = E0.a
let e1_b = E1.b
f(p: e0_a) // prints "E0.a"
f(p: e1_b) // prints "E1.b"
我希望能够打印一个描述p
形式参数的字符串:
“ Name of type implementing P
。case of P
”
如函数所示f()
,这工作得很好,我得到了我想要的输出。
如果可能的话,我想做的是实现一个生成相同字符串的CustomStringConvertible
扩展。P
这可能吗?
这是一种行不通的方法:
protocol P: CustomStringConvertible { }
extension P {
var description: String { return "\(type(of: self).\(self)" }
}
这不起作用,因为\(self)
导致description
递归调用自身直到堆栈溢出。
这是另一种不起作用的方法:
protocol P: CustomStringConvertible { }
extension P where Self: RawRepresentable {
var description: String { return "\(type(of: self)).\(self.rawValue)" }
}
这种方法不起作用,因为E0
is not RawRepresentable
。引擎盖下有一些魔法,即使枚举没有,Swift 也可以打印枚举的案例名称rawValue
,但我不知道如何访问它。使用类似Mirror(reflecting: p).description
打印 p 的类型,而不是枚举的案例名称。
谢谢你的任何想法。正如我所说,它可以在接收 a 的函数中完成P
,但 aCustomStringConvertible
会更干净。
解决方案
推荐阅读
- xamarin.forms - 将记录设置为在 Xamarin 表单中一次显示 10 条记录的列表视图
- java - 更新 blob 内容时未触发 DatabaseChangeNotification
- c# - 应用程序处于中断模式 - 无法诊断代码
- javascript - 如何用 Jquery 替换两个表行?
- .net - 我正在优化数据库查询以在我面临性能问题的应用程序中进行搜索操作
- html - 制作横幅上下比例
- ruby-on-rails - 简单表格时间使用不正确的区域
- pytorch - 在 Pytorch 0.4、python 2.7 上获取 FileNotFoundError 异常 - 应用修复后
- excel - excel连接字符串-相对路径
- windows - 更改锁定屏幕 Windows 10 powershell