Plain array in Swift vs 'NSMutableArray'?

So in Swift, what's the difference between

var arr = ["Foo", "Bar"] // normal array in Swift

      

and

var arr = NSMutableArray.array() // 'NSMutableArray' object

["Foo", "Bar"].map {
    arr.addObject($0)
}

      

not being different implementations of the same thing. Both have all the basic functionality you might need ( .count

, the ability to insert / delete objects, etc.).

NSMutableArray

was invented back in the days of Obj-C, apparently to provide a more modern solution instead of the usual C-style arrays. But how does it compare to Swift's built-in array?

Which one is safer and / or faster?

+3


source to share


2 answers


The most important difference, in my opinion, is that NSMutableArray is a class type and Array is a value type. Ergo, NSMutableArray will be passed as a reference, whereas Swift Array will be passed by value.

Further NSMutableArray is a subclass of NSObject, whereas Array has no parent class. - this means you have access to all NSObject methods and other goodies when using NSMutableArray.

NSMutableArray will not be copied, if you change it will Swift Array.



Which one is best depends on your application.

I find (when working with UIKit and Cocoa touch) that NSMutableArray is great when I need a persistent model, whereas Array is great for performance and throws away arrays.

These are just my initial thoughts, I'm sure someone from the community has much deeper insight to offer.

+9


source


Reference Type When :( NSMutableArray)

NSObject subclasses must be class types Instance identity comparison with === makes sense You want to create shared, mutable state

Value type When: (Swift array)

Comparing instance data with == makes sense (Equatable protocol) You want copies to have independent state
Data will be used in code for multiple threads (avoid explicit synchronization)

Interestingly, the Swift standard library strongly supports value types: primitive types (Int, Double, String, ...) are value types Standard collections (Array, Dictionary, Set, ...) are value types



Apart from what is shown above, the choice really depends on what you are trying to implement. Typically, if there is no specific constraint that forces you to choose the type of reference, or you are not sure which option is best for your particular use case, you can start by implementing your data structure using a value type. If necessary, you can subsequently convert it to a reference type with relatively little effort.

Output:

Reference types incur more memory overhead , from reference counting as well as storing its data on the heap.

It's worth knowing that copy value types are relatively cheap in Swift .

But it's important to remember that if your value types get too large, the copy-on-copy cost may become greater than the cost of using reference types.

+1


source







All Articles