Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 581
Igor Palaguta Avatar asked Jan 08 '23 13:01

Igor Palaguta


1 Answers

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;
like image 52
newacct Avatar answered Jan 13 '23 22:01

newacct