NSSet<NSString *> *foo = [[NSSet alloc] initWithArray:@[]];
但是如果你试图在Swift中专门化NSSet:
let foo:NSSet<String> = NSSet(array: [])
你得到这个:不能专门化非泛型类型’NSSet’
现在,我知道Swift有一个通用的Set类并且是NSSet的桥接器,但是我正在为NSManagedObject子类做这个,所以我也需要支持NSOrderedSet,而且在Swift中还没有有序集.
我的问题是,这是故意还是这是一种疏忽?是否有任何理由NSSet不会在Swift中作为泛型类公开,而是在ObjC中?
All
NSSet
objects can be bridged to Swift sets,so the Swift compiler replaces theNSSet
class withSet<AnyObject>
when it imports Objective-C APIs.
因此,正如matt在他的回答中已经说过的那样,Swift语言中的NSSet与Set< AnyObject>相同,并且与当前版本的Objective-C语言中的NSSet不同,即使它们具有相同的内容名称.
继续引用文档:
You can also create an
NSSet
object directly from a Swift array literal,following the same bridging rules outlined above. When you explicitly type a constant or variable as anNSSet
object and assign it an array literal,Swift creates anNSSet
object instead of a Swift set.
换句话说,它创建了一个类型为Set< AnyObject>的对象,这就是Swift编译器给出错误的原因(NSSet不是通用的,因为它对应于Object-C中的通用NSSet,但已经在实例化了输入AnyObject).
你能做的就是写下这样的东西:
let foo = NSSet(array: ["one","two","three"]) // foo has now the type NSSet<AnyObject>,which corresponds to Set<AnyObject> let bar = foo as! Set<String> // bar has now the type Set<String>,which has no correspondent as NSSet<...> in Swift