mea*_*ers 1 generics ios swift rawrepresentable
enum我想要一个通用函数,它可以通过提供枚举类型和Int原始值来实例化我拥有的几种不同类型的对象。这些enum也是CustomStringConvertible。
我试过这个:
func myFunc(type: CustomStringConvertible.Type & RawRepresentable.Type, rawValue: Int)
Run Code Online (Sandbox Code Playgroud)
这会导致 3 个错误:
现在忘记“CustomStringConvertible”,我也尝试过:
private func myFunc<T: RawRepresentable>(rawValue: Int, skipList: [T]) {
let thing = T.init(rawValue: rawValue)
}
Run Code Online (Sandbox Code Playgroud)
但是,尽管代码完成建议这样做,但会导致以下错误T.init(rawValue:):
我怎样才能形成这样一个有效的通用函数?
问题在于,这可能与当前的类型限制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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
705 次 |
| 最近记录: |