实现Objective-C协议的Swift泛型类

时间:2023-01-15 17:47:34

My intention is to create a generic class in Swift which conforms to an Objective-C protocol:

我的目的是创建一个符合Objective-C协议的Swift通用类:

The class is:

类是:

class BaseViewFactoryImpl<T> : NSObject, BaseView {
  func getNativeInstance() -> AnyObject {
    return String("fsd")
  }
}

The protocol BaseView is:

协议BaseView是:

@protocol BaseView < NSObject >

- (id)getNativeInstance;

@end

The compiler tells me:

编译器告诉我:

Type 'BaseViewFactoryImpl<T>' does not conform to protocol 'BaseView'

If I delete <T> then there is no error.

如果我删除 ,则没有错误。

What is wrong here? How can I get the correct generic class implementation?

什么是错误的吗?如何获得正确的泛型类实现?

2 个解决方案

#1


0  

If you create a new generic view model, when you try to create any subclass of the generic view model, you need to declare the subclass as a generic class as well. It's kind of annoy.

如果您创建一个新的泛型视图模型,当您尝试创建泛型视图模型的任何子类时,您也需要将子类声明为泛型类。这是骚扰。

For a better way, you can use typealias to declare the instance's type instead of using generic:

更好的方法是使用typealias来声明实例的类型,而不是使用泛型:

protocol BaseView {
    typealias T
    func getNativeInstance() -> T!
}

class StringViewModel : BaseView {

    typealias T = String

    func getNativeInstance() -> String! {
        return T()
    }

}

#2


0  

//BaseViewFactory.swift

/ / BaseViewFactory.swift

class BaseViewFactoryImpl<T> : NSObject, BaseView {
    func getNativeInstance() -> AnyObject {
        return String("fsd")
    }

//BaseViewProtocol.h

/ / BaseViewProtocol.h

@protocol BaseView <NSObject>

- (id)getNativeInstance;

@end

//BridgingHeader.h

/ / BridgingHeader.h

#import "BaseClassProtocol.h"

Your code should work. Have you created the bridging header to import the obj-C protocol file?

您的代码应该工作。您是否已经创建了导入objc - c协议文件的桥接头?

#1


0  

If you create a new generic view model, when you try to create any subclass of the generic view model, you need to declare the subclass as a generic class as well. It's kind of annoy.

如果您创建一个新的泛型视图模型,当您尝试创建泛型视图模型的任何子类时,您也需要将子类声明为泛型类。这是骚扰。

For a better way, you can use typealias to declare the instance's type instead of using generic:

更好的方法是使用typealias来声明实例的类型,而不是使用泛型:

protocol BaseView {
    typealias T
    func getNativeInstance() -> T!
}

class StringViewModel : BaseView {

    typealias T = String

    func getNativeInstance() -> String! {
        return T()
    }

}

#2


0  

//BaseViewFactory.swift

/ / BaseViewFactory.swift

class BaseViewFactoryImpl<T> : NSObject, BaseView {
    func getNativeInstance() -> AnyObject {
        return String("fsd")
    }

//BaseViewProtocol.h

/ / BaseViewProtocol.h

@protocol BaseView <NSObject>

- (id)getNativeInstance;

@end

//BridgingHeader.h

/ / BridgingHeader.h

#import "BaseClassProtocol.h"

Your code should work. Have you created the bridging header to import the obj-C protocol file?

您的代码应该工作。您是否已经创建了导入objc - c协议文件的桥接头?