将泛型子类型约束传递给方法时Swift编译时错误 [英] Swift compile time error when passing object with generics subclass type constraint to method

查看:133
本文介绍了将泛型子类型约束传递给方法时Swift编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类型的类,泛型类型有一个子类型约束。然后我尝试将一个类的实例传递给一个方法,但最终出现以下编译时错误:

 无法转换值类型'B< SomeType>'到期望的参数类型'B< NSObject>'

简单的例子:

  class A:NSObject {

func testB(b:B< NSObject>) {
$ b}
}

class B< SomeType:NSObject> ;: NSObject {

func test(){
让a = A()
a.testB(b:self)//< -----上面提到的错误在这里显示
}
}

由于 SomeType 保证是 NSObject ,我预计编译器可以将 B > 转换为 B< NSObject> 并传递它。



类A只关心B的 SomeType NSObject的而不是关于 SomeType 的实际类型。这就好像一个函数需要一个 UIView 参数,并且你传递了一个 UILabel

解决方案

更改:

  func testB(b: B< NSObject>){

}

收件人:

  func testB< SomeType:NSObject>(b:B< SomeType>){

}

这将起作用,因为 SomeType 约束为 NSObject ,不等于 NSObject

所以你的函数的 SomeType 也应该约束为 NSObject

func testB< SomeType:NSObject>(b:B< SomeType>){...}


I have a class with a generic type and the generic type has a subclass type constraint. I then try and pass an instance of the class to a method but end up with the following compile time error:

 Cannot convert value of type 'B<SomeType>' to expected argument type 'B<NSObject>'

Below is a simple example:

class A: NSObject {

    func testB(b: B<NSObject>) {

    }
}

class B<SomeType: NSObject>: NSObject {

    func test() {
        let a = A()
        a.testB(b: self) // <----- The error noted above is shown here
    }
}

Because SomeType is guaranteed to be a subclass of NSObject, I would have expected the compiler would be ok with converting B<SomeType> to B<NSObject> and passing it along.

Class A only cares that B's SomeType is a subclass of NSObject and not about the actual type of SomeType. It's like if a function were to take a UIView parameter and you pass in a UILabel.

解决方案

Change:

func testB(b: B<NSObject>) {

}

To:

func testB<SomeType: NSObject>(b: B<SomeType>) {

}

This will work, because SomeType is constrain to NSObject, not equal to NSObject.

So your function's SomeType should be constrain to NSObject too:

func testB<SomeType: NSObject>(b: B<SomeType>) { ... }

这篇关于将泛型子类型约束传递给方法时Swift编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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