swift - 编写一个接受任何由 CustomStringConvertible 表示的 RawRepresentable 值的通用函数时出现问题
问题描述
我正在尝试编写一个函数,该函数接受任何由 CustomStringConvertible 表示的 RawRepresentable 值。我试着写这个:
enum MyEnum: String {
case a = "someString"
}
func myFunction<R: RawRepresentable>(val: R) where R.RawValue == CustomStringConvertible {
print(val.rawValue.description)
}
myFunction(val: MyEnum.a)
但是我收到以下错误:
Global function 'myFunction(val:)' requires the types 'String' and 'CustomStringConvertible' be equivalent
这很奇怪,因为String
确实符合CustomStringConvertible
.
符合RawValue
to 只是String
有效,但是,我想让它与其他CustomStringConvertible
.
为什么这不能编译,有没有办法可以实现?
解决方案
你应该说它符合协议
where R.RawValue: CustomStringConvertible
现在它也适用于其他类型
enum MyEnum2: Int {
case one = 1
}
myFunction(val: MyEnum2.one)
推荐阅读
- node.js - Node.js - XML 验证
- java - 简单的控制台程序,但我需要 GoF 模式来进行搜索算法
- ios - iOS 14 和 Swift 5 更新
- javascript - 为什么反应路由器不显示所需的元素?
- python - 如何将张量中的每个向量乘以向量的每个元素
- google-cloud-platform - 主服务器上 Cloud Build 失败的监控警报
- ios - 如何在 Swift5.3 中使用 AppDelegate 处理 URL
- c++ - 如何将arduino库中的字符串转换为c ++中的std :: string
- c# - 如何在 Azure 应用服务中显示用户友好的错误
- python - 如何将 .pyc 文件编译为 .exe 文件?我不能使用 auto-py-to-exe 或 pyinstaller,因为它们不接受字节