Why can't I specialize in NSSet in Swift?

So, as in xcode 7, foundation collections are generics that are great, so you can do it in ObjC:

NSSet<NSString *> *foo = [[NSSet alloc] initWithArray:@[]]; 

But if you try to specialize NSSet in Swift:

 let foo:NSSet<String> = NSSet(array: []) 

You will receive the following: Cannot specialize non-generic type 'NSSet'

Now I know that Swift has a Set class, which is common and a bridge for NSSet , but I do it for subclasses of NSManagedObject , so I need to support NSOrderedSet , and also there is no ordered set in Swift yet.

My question is, is it intentional or is it supervision? Is there any reason that NSSet will not display as a generic class in Swift, but will be in ObjC?

+6
source share
1 answer

As the documentation says:

All NSSet objects can be connected to Swift sets, so the Swift compiler replaces the NSSet Set<AnyObject> class when importing the Objective-C API.

So, since Matt already said in other words in his answer, the NSSet inside the Swift language is identical to Set<AnyObject> , and this is not the same as the NSSet in the current version of the Objective-C language even if they have the same name.

Continuing to refer to the documentation:

You can also create an NSSet object directly from a literal of a Swift array, following the same bridge rules described above. When you explicitly enter a constant or variable as an NSSet object and assign an array literal to it, Swift creates an NSSet object instead of a Swift set.

In other words, it creates an object of type Set<AnyObject> , and this is the cause of the error set by the Swift compiler ( NSSet not common, since it corresponds to the general NSSet in Object-C, but an instance of type AnyObject has already been created).

What you can do is write something like:

 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 
+6
source

All Articles