As the title says, what's the difference between Array vs NSArray vs [AnyObject]?
Also, what is most recommended way of approaching this. What i mean recommended is, what's the easiest implementation. Thank you.
Swift provides two special types for working with nonspecific types: Any can represent an instance of any type at all, including function types. AnyObject can represent an instance of any class type.
The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.
The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.
In Swift, the NSArray class conforms to the ArrayLiteralConvertible protocol, which allows it to be initialized with array literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).
Array
is a struct, therefore it is a value type in Swift. NSArray
is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject>
. NSMutableArray
is the mutable subclass of NSArray
.
var arr : NSMutableArray = ["Pencil", "Eraser", "Notebook"] var barr = ["Pencil", "Eraser", "Notebook"] func foo (var a : Array<String>) { a[2] = "Pen" } func bar (a : NSMutableArray) { a[2] = "Pen" } foo(barr) bar(arr) println (arr) println (barr)
Prints:
( Pencil, Eraser, Pen ) [Pencil, Eraser, Notebook]
Because foo
changes the local value of a
and bar
changes the reference. It will also work if you do let arr
instead of var
as with other reference types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With