首页 > 解决方案 > 编写一个接受任何由 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.

符合RawValueto 只是String有效,但是,我想让它与其他CustomStringConvertible.

为什么这不能编译,有没有办法可以实现?

标签: swiftgenericsswift-protocols

解决方案


你应该说它符合协议

where R.RawValue: CustomStringConvertible 

现在它也适用于其他类型

enum MyEnum2: Int {
    case one = 1
}

myFunction(val: MyEnum2.one)

推荐阅读