gpt4 book ai didi

swift - Swift 函数中的泛型和协议(protocol)一致性

转载 作者:行者123 更新时间:2023-11-28 09:05:14 24 4
gpt4 key购买 nike

我刚刚读了Brent Simmon's post on a problem he is having with Swift我想我找到了答案:通用协议(protocol)一致性。

他遇到的问题是他有一个协议(protocol)Value,它符合Equatable。他有另一个协议(protocol),Smashable,它需要函数 valueBySmashingOtherValue。他有一个结构 Bar,它实际上符合 SmashableValue

在采用通用类型 T 的后续函数中,返回一个 Bar。 Swift 类型系统提示 'Bar' 不能转换为 'T'

这是我认为可行的方法:

protocol Value: Equatable { }

protocol Smashable {
func valueBySmashing​OtherValue​<T: Value, Smashable>(value: T) -> T
}

struct Bar: Smashable, Value {
func valueBySmashing​OtherValue​<T: Value, Smashable>(value: T) -> T {
return value;
}
}

func ==(lhs: Bar, rhs: Bar) -> Bool {
return false
}

struct Foo {
func valueBySmashing​OtherValue​<T: Value, Smashable>(value: T) -> T {
return Bar()
}
}

使通用类型 T 符合 ValueSmashableBar 实际上符合这些,因此类型系统应该可以正常返回它。

但事实并非如此。为什么?

最佳答案

虽然 Bar 确实符合 ValueSmashable 但它不是唯一满足的类型那些标准。我可以创建一个新类型(使用最新的 Swift 语法):

struct NotBar: Smashable, Value {
func valueBySmashing​OtherValue​<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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com