我有一个枚举定义为:
enum Context<T> {
case some(T)
case error(Error)
case none
}
为了让它可以用 nil 表达,我创建了这个扩展:
extension Context: ExpressibleByNilLiteral {
init(nilLiteral: ()) {
self = .none
}
}
然后我有另一个类公开一个方法,该方法应将上下文作为参数:
func start<T>(context: Context<T>)
如果我尝试使用它传递 nil 作为上下文,编译器会向我显示一条错误消息:
Generic parameter 'T' could not be inferred
我已经看到了一些关于它的答案,但它们似乎不起作用。
我不明白是否不可能这样做,或者我是否以错误的方式这样做。
最佳答案
类型推断器需要判断T
从看到nil
就不可能这样做(或 .none
,就此而言)——它应该选择哪种类型?
你需要制作T
具体的,例如通过
start(context: nil as Context<Int>)
再次注意传递.none
有同样的问题所以问题不在ExpressibleByNilLiteral
完全没有。
在实际使用中,可能会通过其他参数甚至返回值来判断T
.例如,如果你有一个函数
func get<T>(context: Context<T>) throws -> T?
然后像这样的行
let v: Int? = get(context: nil)
工作得很好。
旁注:为什么要使用 nil
文字作为 .none
的别名?使用后者可以避免在阅读代码时产生混淆:let v: Context<Int> = nil
乍一看,Swift 无效。
关于swift - 通用枚举在 swift 中符合 ExpressibleByNilLiteral,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47348856/