Swift协变泛型函数:占位符类型是另一个的子类 [英] Swift covariant generic function : placeholder type is a subclass of another

查看:81
本文介绍了Swift协变泛型函数:占位符类型是另一个的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,需要两个类作为参数.我希望第一个成为NSObject的子类(到目前为止非常简单),第二个成为另一个的子类或相同的类–我该如何表达呢?

I have a function that takes two classes as parameters. I'd like the first one to be a subclass of NSObject (pretty straightforward so far), and the second to be a subclass or the same class as the other – how can I express this ?

class MyClass: NSObject {}
class MySubClass: MyClass {}
myFunction(MyClass.Type, MySubClass.Type)

MyFunction定义如下:

With MyFunction defined as follows:

func myFunction<T: NSObject>(param1: T.Type, param2: T.Type)

不幸的是,由于MyClass和MySubClass不相同(我对myFunction的定义期望它们完全相同),因此'(MyClass.Type,MySubClass.Type)'的调用错误无法转换为'((MyClass.Type,MyClass.Type)'.

Unfortunately, because MyClass and MySubClass are not the same (and my definition of myFunction expects them to be the exact same), the invocation errors with '(MyClass.Type, MySubClass.Type)' is not convertible to '(MyClass.Type, MyClass.Type)'.

如何表达myFunction的第二个参数的类型不必与第一个参数相同,而只是__kindof的事实,正如人们会在Objective-C中编写的那样?

How to express the fact that the type of the second parameter of myFunction needs not be the same as the first, but merely __kindof, as one would've written it in Objective-C ?

看来,我的问题尚不清楚. 以下是不够的: func myFunction<T:NSObject,U:NSObject>(param1: T.Type, param2: U.Type) ...因为它允许我将定义为class AnotherClass : NSObject,并将其作为myFunction(param1: MyClass.Type, param2: AnotherClass.Type)调用.在这种情况下,AnotherClass在MyClass的继承层次结构之外.

EDIT : As it seems, my question is not clear. The following is not enough : func myFunction<T:NSObject,U:NSObject>(param1: T.Type, param2: U.Type) ... because it allows me to invoke it as myFunction(param1: MyClass.Type, param2: AnotherClass.Type) with AnotherClass defined as class AnotherClass : NSObject. In that case, AnotherClass is outside of MyClass' inheritance hierarchy.

这就是为什么我给出__kindof的示例的原因,该示例仅表示(在ObjC中)即协变泛型.

That's why I gave the example of __kindof, which expresses just that (in ObjC) – that is, covariant generics.

推荐答案

这是您所需要的吗?运行它没有问题.

Is this what you need or not? There is no problem to run it.

class MyClass: NSObject {}
class MySubClass: MyClass {}

func myFunction<T: NSObject>(param1: T.Type, param2: T.Type){
print("OK")
}
myFunction(param1: MyClass.self, param2: MySubClass.self as MyClass.Type)

myFunction(param1: type(of: MyClass()), param2: type(of: MySubClass()))

这篇关于Swift协变泛型函数:占位符类型是另一个的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆