[英]How to specify the type of a function parameter with combined type CustomStringConvertible and RawRepresentable?
I want a generic function that can instantiate object of a few different enum
types I have by supplying the enum type and the Int
raw-value.我想要一个通用函数,它可以通过提供枚举类型和
Int
原始值来实例化我拥有的几种不同enum
类型的对象。 These enum
s are also CustomStringConvertible
.这些
enum
也是CustomStringConvertible
。
I tried this:我试过这个:
func myFunc(type: CustomStringConvertible.Type & RawRepresentable.Type, rawValue: Int)
which results in 3 errors:这导致 3 个错误:
Forgetting about 'CustomStringConvertible` for now, I also tried:暂时忘记“CustomStringConvertible”,我也尝试过:
private func myFunc<T: RawRepresentable>(rawValue: Int, skipList: [T]) {
let thing = T.init(rawValue: rawValue)
}
But, although code completion suggests it, leads to an error about the T.init(rawValue:)
:但是,尽管代码完成建议它,导致关于
T.init(rawValue:)
的错误:
How can I form a working generic function like this?我怎样才能形成这样的工作通用函数?
The issue is that T.RawValue
can be something else than Int
with your current type constraints.问题是
T.RawValue
可以是Int
以外的其他东西,并且具有您当前的类型约束。 You need to specify that T.RawValue == Int
in order to pass your rawValue: Int
input parameter to init(rawValue:)
.您需要指定
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.