如何限制泛型函数的关联类型

时间:2018-12-14 05:48:31

标签: swift generics protocols associated-types

我正在尝试采用两个协议,它们都具有相同的关联类型并返回相同的类型,但是没有运气。

protocol MyProtocol {
    associatedtype AssociatedType
}

func myFunc<T: MyProtocol, R: MyProtocol>(arg: T) -> R
    where T.AssociatedType == R.AssociatedType {
        return arg //Error-> Cannot convert return expression of type 'T' to return type 'R'
}

在Swift中这样的事情可能吗?

1 个答案:

答案 0 :(得分:2)

两个类型(分别称为TR)不一定是等效的,只是因为它们遵循相同的协议并使用相同的关联类型。

通过这种推理,Array<Int>Set<Int>相同,并且应该可以自由互换,因为它们都符合Collection,其中Element是{{1} }。

这是另一个反例:

Int
  

由于信号protocol MyProtocol { associatedtype AssociatedType init() } protocol MySubProtocol1: MyProtocol where AssociatedType == Int {} protocol MySubProtocol2: MyProtocol where AssociatedType == Int {} struct S1: MySubProtocol1 {} struct S2: MySubProtocol2 {} func myFunc<T: MyProtocol, R: MyProtocol>(arg: T) -> R where T.AssociatedType == R.AssociatedType { return arg as! R // Let's see what would happen. Don't do this! } func produce<T: MySubProtocol1>(type: T.Type) -> T { return T() } func consume<T: MySubProtocol2>(arg: T, ofType: T.Type) { print(arg) } consume(arg: myFunc(arg: produce(type: S1.self)), ofType: S2.self)

而终止      

无法将类型ABORT TRAP (6)'main.S1')的值强制转换为0x100e44210'main.S2')。

相关问题