据我所知,在Swift-C中没有一个内置的机制来指定放入NSArray的对象的类型,但看起来Swift做了你想要的事情,如果这有帮助的话: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_172 在一个稍微相关的注意事项上,这里有一篇关于强制只将特定类型的对象插入到子类NSMutableArray中并在尝试插入 * 错误 * 对象类型时抛出异常的文章: NSMutableArray - force the array to hold specific object type only
// The only limitation is that MyGenericType must be an object.
// Exclude __covariant if you are doing something with the same interface in
// a different part of your code
@interface MyGenericClass<__covariant MyGenericType> : NSObject
// Your code here
@end
@interface NSArray<__covariant ObjectType> : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>
// the code
@end
// A different part of the code using the same interface, so __covariant is excluded.
@interface NSArray<ObjectType> (NSExtendedArray)
// more code
@end
4条答案
按热度按时间q9rjltbz1#
据我所知,在Swift-C中没有一个内置的机制来指定放入NSArray的对象的类型,但看起来Swift做了你想要的事情,如果这有帮助的话:
https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_172
在一个稍微相关的注意事项上,这里有一篇关于强制只将特定类型的对象插入到子类NSMutableArray中并在尝试插入 * 错误 * 对象类型时抛出异常的文章:
NSMutableArray - force the array to hold specific object type only
wwwo4jvm2#
遗憾的是,Objective-C中没有泛型。
7nbnzgx93#
你可以使用
NSArray<MyClass*> *myClassArray
来声明MyClass的数组。如果你想创建一个自己的数组,你可以这样做。字符串
__covariant
的这种用法可以在NSArray
和更多的接口中找到。这就是它在NSArray接口中的使用方式。
型
MyGenericType
必须是对象的原因是因为Objective C没有任何类型,所以在实现中使用id
。但是数字可以用NSNumber
表示。您也可以指定多个__covariants
,只需用逗号分隔即可。或者你可以去调查斯威夫特
xienkqul4#
现在Xcode 7支持一些标准集合的泛型(例如NSArrays)。所以你可以创建一个数组并提供这样的存储对象:
字符串