【发布时间】:2019-05-14 18:42:32
【问题描述】:
我有一个泛型类型
enum ResultState<T> {
case found(T)
}
有一些扩展
extension ResultState {
func hello() { print("Hello") }
}
extension ResultState where T: Collection {
func hello() { print("Hello, collection") }
}
这些工作完美无缺,完全符合我的预期:
ResultState.found(1).hello() // prints "Hello"
ResultState.found([1]).hello() // prints "Hello, collection"
但是,如果它们是从另一个泛型函数中调用的,它的行为就不一样了
func myFunction<T>(_ state: ResultState<T>) {
state.hello()
}
例如,
myFunction(ResultState.found(1)) // prints "Hello"
myFunction(ResultState.found([1]) // prints "Hello"
现在,每次都会调用基本版本的 hello,尽管检查 myFunction 中的 T 显示它肯定是 Array<Int>。
这是预期的 Swift 行为吗?
如果是这样,我将如何解决它 - 如何从 myFunction 中调用正确版本的 hello?
【问题讨论】:
-
奇怪!!!
标签: swift generics overriding