编写通用函数时出现问题,该函数接受 CustomStringConvertible 可 RawRepresentable 的任何值

Problem writing a generic function that accepts any value that is RawRepresentable by a CustomStringConvertible

我正在尝试编写一个函数,该函数接受 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 仅适用于 String 是可行的,但是,我想让它与其他 CustomStringConvertible.

一起使用

为什么不能编译,有什么方法可以实现吗?

你应该说它符合协议

where R.RawValue: CustomStringConvertible 

现在它也适用于其他类型

enum MyEnum2: Int {
    case one = 1
}

myFunction(val: MyEnum2.one)