简体   繁体   English

协议和泛型类型中的Swift类型

[英]Swift typealias in protocol and generic types

I have a protocol, that has a typealias: 我有一个协议,有一个typealias:

protocol Fooable {
    typealias T: Equatable
    func makeFoo() -> T
}

I expect, that all types, that conforms to it will return Equatable values from makeFoo . 我希望,符合它的所有类型都将从makeFoo返回Equatable值。

Now I'd like to make an array extension, which stores Fooable values: 现在我想创建一个数组扩展,它存储Fooable值:

extension Array where Element: Fooable {

    func arrayFoo<F: Foobable, S>(array: Array<F>, transform: (Element, [F]) -> S) -> [S] {

I expect, that given array A, which contains Fooable elements and array B, which contains Fooable elements I can make: 我希望,给定数组A,其中包含Fooable元素和数组B,其中包含我可以制作的Fooable元素:

a.arrayFoo(b, {...})

I have a part of arrayFoo function: 我有一部分arrayFoo函数:

var leftGenerator = self.generate()
var rightGenerator = array.generate()

if let leftValue = leftGenerator.next(), rightValue = rightGenerator.next() {
    let leftFoo = leftValue.makeFoo()
    let rightFoo = rightValue.makeFoo()

    if leftFoo == rightFoo {

I expect leftFoo and rightFoo to be Equatable, because they are produced by makeFoo() , which should return Equatables. 我希望leftFoorightFoo是Equatable,因为它们是由makeFoo() ,它应该返回Equatables。

But Swift complains: Binary operator == cannot be applied to operands of type Element.T and FT 但Swift抱怨: Binary operator == cannot be applied to operands of type Element.T and FT

Any ideas or workarounds? 任何想法或解决方法?

In your arrayFoo() method, both array and self are arrays of Fooable elements, but not necessarily with the same underlying type T , ie Element.T and FT are unrelated types. 在你的arrayFoo()方法中, arrayself都是Fooable元素的数组,但不一定具有相同的底层类型T ,即Element.TFT是不相关的类型。

You can fix that with an additional constraint where FT == Element.T on the type placeholders: 您可以使用类型占位符上的where FT == Element.T附加约束来解决此问题:

func arrayFoo<F: Fooable, S where F.T == Element.T >(array: Array<F>, transform: (Element, [F]) -> S) -> [S] {
    // ...
}

I think that problem is inside Equatable protocol, look in it's declaration: 我认为这个问题在Equatable协议中,查看它的声明:

@warn_unused_result
public func ==(lhs: Self, rhs: Self) -> Bool

You should override func == and provide some result for this, or Swift compiler doesn't know, hot to compare it. 你应该覆盖func ==并为此提供一些结果,或者Swift编译器不知道,热点比较它。 You use generic type, it's not settled how to compare Int and String for example 您使用泛型类型,例如,如何比较IntString并未解决

let t = 0
let a = "string"
if t == a { // error
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM