我想要一个泛型函数,它可以通过提供枚举类型和enum原始值来实例化几种不同Int类型的对象。这些enums也是CustomStringConvertible。
我试过这个:
func myFunc(type: CustomStringConvertible.Type & RawRepresentable.Type, rawValue: Int)这将导致以下三个错误:
非协议,非类类型'CustomStringConvertible.Type‘不能在协议约束的非类类型中使用'RawRepresentable.Type’不能用于协议约束类型
。
现在,我忘记了“CustomStringConvertible`”,我还尝试了:
private func myFunc<T: RawRepresentable>(rawValue: Int, skipList: [T]) {
let thing = T.init(rawValue: rawValue)
}但是,尽管代码完成表明了这一点,但会导致有关T.init(rawValue:)的错误。
的参数列表调用'init‘
我如何才能形成这样的通用函数?
发布于 2020-03-27 10:30:01
问题是,在当前的类型约束下,T.RawValue可以是Int以外的其他东西。您需要指定该T.RawValue == Int,以便将rawValue: Int输入参数传递给init(rawValue:)。
func myFunc<T: RawRepresentable & CustomStringConvertible>(rawValue: Int, skipList: [T]) where T.RawValue == Int {
let thing = T.init(rawValue: rawValue)
}https://stackoverflow.com/questions/60884057
复制相似问题