Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a generic mutable array in Swift?

I tried this:

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

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

Why?

like image 211
János Avatar asked Aug 26 '14 14:08

János


1 Answers

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.

like image 150
Antonio Avatar answered Sep 23 '22 17:09

Antonio