作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚刚读了Brent Simmon's post on a problem he is having with Swift我想我找到了答案:通用协议(protocol)一致性。
他遇到的问题是他有一个协议(protocol)Value
,它符合Equatable
。他有另一个协议(protocol),Smashable
,它需要函数 valueBySmashingOtherValue
。他有一个结构 Bar
,它实际上符合 Smashable
和 Value
。
在采用通用类型 T
的后续函数中,返回一个 Bar
。 Swift 类型系统提示 'Bar' 不能转换为 '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
实际上符合这些,因此类型系统应该可以正常返回它。
但事实并非如此。为什么?
最佳答案
虽然 Bar
确实符合 Value
和 Smashable
但它不是唯一满足的类型那些标准。我可以创建一个新类型(使用最新的 Swift 语法):
struct NotBar: Smashable, Value {
func valueBySmashingOtherValue<T:Value where T:Smashable>(value: T) -> T {
return value;
}
}
func ==(lhs: NotBar, rhs: NotBar) -> Bool {
return true
}
如果我将 NotBar
的实例传递给 Foo.valueBySmashing OtherValue
,那么我会期望返回一个 NotBar
。编译器知道这一点,所以它不允许您返回 Bar
。
关于swift - Swift 函数中的泛型和协议(protocol)一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30980805/
我是一名优秀的程序员,十分优秀!