Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Swift: Difference between Array VS NSArray VS [AnyObject]

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.

like image 325
shle2821 Avatar asked Mar 05 '15 23:03

shle2821


People also ask

What is the difference between any and AnyObject in Swift?

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.

What's a difference between NSArray and NSSet?

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.

What is difference between NSArray and NSMutableArray?

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.

Can we use NSArray in Swift?

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).


1 Answers

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.

like image 182
Krzak Avatar answered Sep 20 '22 21:09

Krzak