Array and list question

Since arrays in Swift are value types, there are many situations that I want something like a list (reference typed). So my questions are:


Does Swift has such a class?

Or is it possible to declare a reference to an array instance?

Answered by OOPer in 329648022

Does Swift has such a class?


In Swift Standard Library, NO. In Foundation, there are NSArray and NSMutableArray but I strongly recommend not to use them unless you are forced to use them. (For example, some frameworks might receive NSArray in a hard-to-bridge-from-Swift-Array manner.)


Or is it possible to declare a reference to an array instance?


No. Swift does not have a C++ like reference and cannot get a stable address of Arrays.


(Swift has an inout parameter, it works like a reference, so when passing an Array to functions, you can declare a reference to an array.)


You may need to define a class containing an Array with enough methods to manipulate it.

Or, if you can show some specific use case, there may be other better ways.

use NSMutableArray

Accepted Answer

Does Swift has such a class?


In Swift Standard Library, NO. In Foundation, there are NSArray and NSMutableArray but I strongly recommend not to use them unless you are forced to use them. (For example, some frameworks might receive NSArray in a hard-to-bridge-from-Swift-Array manner.)


Or is it possible to declare a reference to an array instance?


No. Swift does not have a C++ like reference and cannot get a stable address of Arrays.


(Swift has an inout parameter, it works like a reference, so when passing an Array to functions, you can declare a reference to an array.)


You may need to define a class containing an Array with enough methods to manipulate it.

Or, if you can show some specific use case, there may be other better ways.

So, does that mean that the documentation for NSMutableArray should warn against such risk ?


Class NSMutableArray

An object representing a dynamic ordered collection, for use instead of an

Array
variable in cases that require reference semantics.

I am not sure you really understand the risk, but yes, the doc should note about it.

What OOPer said and…

Lots of folks use a

Box
type for this.
class Box<Contents> {
    var contents: Contents
    init(_ contents: Contents) {
        self.contents = contents
    }
}

Whether that’s the right option for you depends on your specific needs. Personally I (almost :-) never use this. Rather, I try to centralise the storage of any mutable data in one place, and then have other parts of my app work on immutable snapshots of that data. Having multiple folks all mutating the same array makes things very confusing IMO.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Array and list question
 
 
Q