14

I tried this:

var ss: [S] = NSMutableArray<S>(capacity: 0)

Compiler says: Cannot specialize non-generic type 'NSMutableArray'

Why?

1 Answer 1

23

NSArray and NSMutableArray are Objective C types, and do not support generics. You can instantiate as swift's native array type:

var settings = [Setting]()

which also can be written as

var settings = Array<Setting>()

Thanks to type inference, you don't have to specify the type, but if you like this are the complete versions:

var settings: [Setting] = [Setting]()
var settings: Array<Setting> = Array<Setting>()

Note that [Setting] and Array<Setting> are interchangeable, meaning they define the same object type, so you can use whichever you like more.

Sign up to request clarification or add additional context in comments.

6 Comments

do you know how can I add elements from an NSOrderedSet to settings?
If not wrong NSOrderedSet has an array property of NSArray type. In order to take advantage of swift generics, you have to loop though that array, cast each element to Setting and add to the settings array
I was able to add sequences also with += array generic operator
Good to know. I didn't know it was possible. Thanks for sharing that :)
You can use NSArray with generics in Objective-C! useyourloaf.com/blog/using-objective-c-lightweight-generics
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.