Igor Palaguta
Igor Palaguta

Reputation: 3579

ObjC generic collection with protocol as parameter is translated as [AnyObject]

Why protocols property is translated as [AnyObject] in swift, not as [P]

@protocol P;
@class C;

@interface TestGenerics: NSObject

@property  NSArray<C*>* classes;
@property NSArray<P>* protocols;

@end

In Swift it look this way:

public class TestGenerics : NSObject {

    public var classes: [C]
    public var protocols: [AnyObject]
}

UPDATE: Found solution

@property NSArray<NSObject<P>*>* protocols;

or like suggested newacct

@property NSArray<id<P>>* protocols;

is translated to:

public var protocols: [P]

Upvotes: 5

Views: 3439

Answers (1)

newacct
newacct

Reputation: 122439

P is not a type in Objective-C. id<P> is an Objective-C type type for anything that conforms to the protocol P. (NSObject<P> * is a type for anything that is an instance of NSObject and conforms to the protocol P, which is slightly different condition.)

So the best way to write it would be:

@property NSArray<id<P>> *protocols;

Upvotes: 9

Related Questions