11

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?

Ortwin Gentz
  • 52,648
  • 24
  • 135
  • 213
  • 5
    It's just not possible with generic classes, see http://stackoverflow.com/questions/26097581/generic-nsoperation-subclass-loses-nsoperation-functionality for a similar issue. – Martin R Apr 17 '15 at 14:37

3 Answers3

1

//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?

Pradeep K
  • 3,671
  • 1
  • 11
  • 15
1

Starting with Swift 3, you need to use Any, not AnyObject, to represent generic id values coming from Objective-C.

This builds with no errors:

class BaseViewFactoryImpl<T> : NSObject, BaseView {
  func getNativeInstance() -> Any {
    return "fsd"
  }
}
Cristik
  • 30,989
  • 25
  • 91
  • 127
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:

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

class StringViewModel : BaseView {

    typealias T = String

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

}
bubuxu
  • 2,187
  • 18
  • 23