简体   繁体   English

Swift 2.0:不能将泛型作为参数传递

[英]Swift 2.0: can not pass generic as a parameter

Why is this not working(even though the Container conforms to Unique protocol.) and how would the best workaround looks like? 为什么这不起作用(即使Container符合Unique协议。)以及最好的解决方法是什么样的?

protocol Unique {
    var uniqueId: String {get}
}

struct Container <T>: Unique {
    typealias UnderlyingObject = T
    var object: UnderlyingObject
    var uniqueId: String
}

func myFunc(protocolClosure: (Unique, Unique) -> Unique) {
    print("...")
}

func problemStartsHere<T,S,U>(paramClosure: (Container<T>, Container<S>) -> Container<U>) {
    myFunc(paramClosure)
}

在此输入图像描述

The problem here is one of variance, though not quite the variance you're looking for. 这里的问题是方差之一,尽管不是你正在寻找的方差。 Since you're passing a closure, you're really trying to make the method signature itself match, rather than the value passed into or return from of the method itself. 因为你传递了一个闭包,所以你真的试图使方法签名本身匹配,而不是传递给方法本身或从方法返回的值。 This could raise problems if, say, myFunc tried invoking the closure using a parameter of a type other than Container<T> - and since it expects any Unique to be acceptable for that invocation, it would compile just fine. 如果,例如, myFunc尝试使用Container<T>以外的类型的参数调用闭包,并且因为它期望任何Unique对于该调用是可接受的,那么这可能会引发问题,它会编译得很好。

The compiler shows this warning for a reason: myFunc expects a closure that works for any kind of Unique not just Container<T> . 编译器显示此警告的原因是: myFunc期望一个闭包适用于任何类型的Unique而不仅仅是Container<T>

You should use a generic version of the function instead: 您应该使用该函数的通用版本:

func myFunc<A: Unique, B: Unique, C: Unique>(protocolClosure: (A, B) -> C) {
    print("...")
}

EDIT: Suppose you wanted to call your function problemStartsHere like this: 编辑:假设您想调用您的函数问题problemStartsHere如下:

problemStartsHere { (c1: Container<Int>, c2: Container<Int>) -> Container<Int> in
    print(c1.object, c2.object)
    return c1
}

Notice that the function uses the Container -specific property object . 请注意,该函数使用Container -specific属性object Not how exactly should the compiler create a closure that works on any Unique ? 不是编译器应该如何创建一个适用于任何Unique的闭包? It can't work like this, because it doesn't make sense, such a function cannot work on any Unique . 它不能像这样工作,因为它没有意义,这样的功能不能在任何Unique上工作。

The problem is the return value. 问题是返回值。 While you can pass any Container<...> to Unique parameter, the return value of type Unique can't be cast to Container<...> . 虽然您可以将任何Container<...>传递给Unique参数,但Unique类型的返回值无法强制转换为Container<...> That's why the closure type (Container<...>, Container<...>) -> Container<...> cannot be cast to (Unique, Unique) -> Unique . 这就是封闭类型(Container<...>, Container<...>) -> Container<...>无法转换为(Unique, Unique) -> Unique

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

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