4

为什么protocols属性在swift中被翻译为[AnyObject],而不是[P]

@protocol P;
@class C;

@interface TestGenerics: NSObject

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

@end

在 Swift 中,它看起来是这样的:

public class TestGenerics : NSObject {

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

更新:找到解决方案

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

或喜欢建议的 newacct

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

被翻译成:

public var protocols: [P]
4

1 回答 1

9

P不是 Objective-C 中的类型。id<P>是符合协议的任何东西的 Objective-C 类型P。(NSObject<P> *是任何属于协议的实例NSObject 符合协议的类型P,条件略有不同。)

所以最好的写法是:

@property NSArray<id<P>> *protocols;
于 2015-09-18T00:45:03.473 回答