【发布时间】:2015-09-07 22:55:13
【问题描述】:
我刚刚阅读了Brent Simmon's post on a problem he is having with Swift,我认为我有答案:通用协议一致性。
他遇到的问题是他有一个协议Value,它符合Equatable。他有另一个协议Smashable,它需要函数valueBySmashingOtherValue。他有一个结构,Bar,实际上符合Smashable 和Value。
在采用泛型类型T 的后续函数中,将返回Bar。 Swift 类型系统抱怨 'Bar' is not convertible to 'T'.
以下是我认为可行的方法:
protocol Value: Equatable { }
protocol Smashable {
func valueBySmashingOtherValue<T: Value, Smashable>(value: T) -> T
}
struct Bar: Smashable, Value {
func valueBySmashingOtherValue<T: Value, Smashable>(value: T) -> T {
return value;
}
}
func ==(lhs: Bar, rhs: Bar) -> Bool {
return false
}
struct Foo {
func valueBySmashingOtherValue<T: Value, Smashable>(value: T) -> T {
return Bar()
}
}
使泛型类型T 符合Value 和Smashable。 Bar 实际上符合这些,所以类型系统应该没问题,你可以返回它。
但事实并非如此。为什么?
【问题讨论】:
-
因为return
T还受输入参数类型的限制,可能与Bar不兼容。