My intention is to create a generic class in Swift which conforms to an Objective-C protocol:
The class is:
class BaseViewFactoryImpl<T> : NSObject, BaseView {
func getNativeInstance() -> AnyObject {
return String("fsd")
}
}
The protocol BaseView
is:
@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?
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:
protocol BaseView {
typealias T
func getNativeInstance() -> T!
}
class StringViewModel : BaseView {
typealias T = String
func getNativeInstance() -> String! {
return T()
}
}
//BaseViewFactory.swift
class BaseViewFactoryImpl<T> : NSObject, BaseView {
func getNativeInstance() -> AnyObject {
return String("fsd")
}
//BaseViewProtocol.h
@protocol BaseView <NSObject>
- (id)getNativeInstance;
@end
//BridgingHeader.h
#import "BaseClassProtocol.h"
Your code should work. Have you created the bridging header to import the obj-C protocol file?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.