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

问题描述 投票:0回答:1

我正在尝试编写一个函数,该函数接受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一起使用。

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

swift generics swift-protocols
1个回答
1
投票

您应该说它符合协议

where R.RawValue: CustomStringConvertible 
© www.soinside.com 2019 - 2024. All rights reserved.