gpt4 book ai didi

swift - Swift 中关联类型的泛型 Where 子句歧义

转载 作者:行者123 更新时间:2023-11-28 15:33:38 25 4
gpt4 key购买 nike

我在 Playground 上写了一些示例代码,想要一个函数来返回两个值之间的距离,这两个值都符合 Swift 中的 Strideable 协议(protocol),这样我就可以使用 distance(to other: Self) -> Self.Stride 功能。我的实现如下:

func distanceFrom<T: Strideable, U>(_ a: T, to b: T) -> U where T.Stride == U
{
return a.distance(to: b)
}

观察这个函数一段时间后,我意识到我不确定 where 子句中使用的是哪个 Stride,是 a 还是 b .据我了解,ab 可以为 Stride 定义不同的关联类型。此外,我还没有做出任何声明来确保 a.Stride == b.Stride,尽管我知道我可以扩展我的 where 子句来做到这一点。

那么,哪一个会被用来检查与 U 的等价性?需要明确的是,问题不在于这个特定的代码块,而在于任何可能存在这种歧义的情况。

最佳答案

ab 是同一类型。如果您希望它们是不同的 Strideable 类型,您可以添加另一个符合 Strideable 的通用参数,这样函数签名如下所示:

func bar<T: Strideable, V: Strideable, U>(_ a: T, to b: V) -> U where T.Stride == U, V.Stride == U {
return a.distance(to: a) //Trivial return statement (see explanation below)
}

虽然前面提到的代码可以编译,但是 return a.distance(to: b) 不会编译,因为它们 (ab)是不同的类型,distance在Swift3中的定义是public func distance(to other: Self) -> Self.Stride(注意Self的使用code> 将 other 限制为与调用此函数的 Strideable 相同的类型)。总之,虽然您可以将 ab 设为不同的类型,但对于您的应用程序来说这样做没有意义。

作为无法调用不同类型的原始发布代码的进一步证据,请参阅附件 Playground screenshot使用不同类型时显示错误。

但是,这在 Playground 上运行良好。

func distanceFrom<T: Strideable, U>(_ a: T, to b: T) -> U where T.Stride == U {
return a.distance(to: b)
}


let doubleFoo: Double = 4.5
let intFoo: Double = 4

let g = distanceFrom(doubleFoo, to: intFoo) // gives me a double of -0.5

希望对您有所帮助。

关于swift - Swift 中关联类型的泛型 Where 子句歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510218/

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