I want to pass my Swift Array
account.chats
to chatsViewController.chats
by reference (so that when I add a chat to account.chats
, chatsViewController.chats
still points to account.chats
). I.e., I don't want Swift to separate the two arrays when the length of account.chats
changes.
9 Answers
For function parameter operator we use:
let
(it's default operator, so we can omit let) to make a parameter constant (it means we cannot modify even local copy);
var
to make it variable (we can modify it locally, but it wont affect the external variable that has been passed to the function); and
inout
to make it an in-out parameter. In-out means in fact passing variable by reference, not by value. And it requires not only to accept value by reference, by also to pass it by reference, so pass it with &
- foo(&myVar)
instead of just foo(myVar)
So do it like this:
var arr = [1, 2, 3]
func addItem(_ localArr: inout [Int]) {
localArr.append(4)
}
addItem(&arr)
print(arr) // it will print [1, 2, 3, 4]
To be exact it's not just a reference, but a real alias for the external variable, so you can do such a trick with any variable type, for example with integer (you can assign new value to it), though it may not be a good practice and it may be confusing to modify the primitive data types like this.
-
13This does not really explain how to use array as an instance variable that is referenced not copied. Jan 15, 2015 at 10:20
-
2I thought inout used a getter and a setter to copy the array to a temporary and then reset it on the way out of the function - i.e. it copies Oct 5, 2015 at 9:41
-
2Actually in-out uses copy-in copy-out or call by value result. However, as an optimization it may use by reference. "As an optimization, when the argument is a value stored at a physical address in memory, the same memory location is used both inside and outside the function body. The optimized behavior is known as call by reference; it satisfies all of the requirements of the copy-in copy-out model while removing the overhead of copying." Mar 28, 2016 at 17:47
-
12In Swift 3,
inout
position has changed, i.e.func addItem(localArr: inout [Int])
Dec 1, 2016 at 5:34 -
4
Structs in Swift are passed by value, but you can use the inout
modifier to modify your array (see answers below). Classes are passed by reference. Array
and Dictionary
in Swift are implemented as structs.
-
2Array is not copied / passed by value in Swift - it has very different behavior in Swift compared to regular struct. See stackoverflow.com/questions/24450284/…– BoonJun 29, 2014 at 15:39
-
16
-
4And I don't recommend using of
NSArray
becauseNSArray
and Swift array have subtle semantic differences (such as reference-type), and that possibly lead you to more bugs.– eonilOct 14, 2014 at 4:00 -
2This was seriously killing me. I was banging my head why things not working the way.– khunshanNov 26, 2015 at 11:30
-
2
Define yourself a BoxedArray<T>
that implements the Array
interface but delegates all functions to a stored property. As such
class BoxedArray<T> : MutableCollection, Reflectable, ... {
var array : Array<T>
// ...
subscript (index: Int) -> T {
get { return array[index] }
set(newValue) { array[index] = newValue }
}
}
Use the BoxedArray
anywhere you'd use an Array
. Assigning of a BoxedArray
will be by reference, it is a class, and thus changes to the stored property, through the Array
interface, will be visible to all references.
-
A bit scary solution :) - not exactly elegant - but it seems it would work. Jan 15, 2015 at 10:21
-
Well, it sure is better than falling back to 'Use NSArray' to get 'pass by reference semantics'!– GoZonerJan 15, 2015 at 16:25
-
17I just have a feeling defining Array as struct instead of class is language design mistake. Jan 18, 2015 at 11:06
-
1I agree. There is also the abomination where
String
is a subtype ofAny
BUT if youimport Foundation
thenString
becomes a subtype ofAnyObject
.– GoZonerJan 18, 2015 at 15:16
For Swift versions 3-4 (XCode 8-9), use
var arr = [1, 2, 3]
func addItem(_ localArr: inout [Int]) {
localArr.append(4)
}
addItem(&arr)
print(arr)
Something like
var a : Int[] = []
func test(inout b : Int[]) {
b += [1,2,3,4,5]
}
test(&a)
println(a)
???
-
4I think the question is asking for a means to have properties of two different objects point to the same array. If that's the case, Kaan's answer is correct: one must either wrap the array in a class, or use NSArray. Jun 16, 2014 at 20:00
-
1right, inout works only for the lifetime of the function body (no closure behaviour) Jun 16, 2014 at 20:01
-
Minor nit: it's
func test(b: inout [Int])
... maybe this is an old syntax; I only got into Swift in 2016 and this answer is from 2014 so maybe things used to be different?– Ray ToalNov 2, 2019 at 18:08
One other option is to have the consumer of the array ask the owner for it as needed. For example, something along the lines of:
class Account {
var chats : [String]!
var chatsViewController : ChatsViewController!
func InitViewController() {
chatsViewController.getChats = { return self.chats }
}
}
class ChatsViewController {
var getChats: (() -> ([String]))!
func doSomethingWithChats() {
let chats = getChats()
// use it as needed
}
}
You can then modify the array as much as you like inside the Account class. Note that this doesn't help you if you want to also modify the array from the view controller class.
Using inout
is one solution but it doesn't feel very swifty to me since arrays are value types. Stylistically I personally prefer to return a mutated copy:
func doSomething(to arr: [Int]) -> [Int] {
var arr = arr
arr.append(3) // or likely some more complex operation
return arr
}
var ids = [1, 2]
ids = doSomething(to: ids)
print(ids) // [1,2,3]
-
1There is a performance downside to this sort of thing. It uses a tad bit less phone battery to just modify the original array :) Jun 12, 2020 at 23:16
-
I respectfully disagree. In this case readability at the call site generally trumps the performance hit. Start with immutable code and then optimize by making it mutable later. There are cases with massive arrays where you are correct but in most apps that's a 0.01% edge case.– ToddHJun 14, 2020 at 6:37
-
1I don't know what you are disagreeing with. There is a performance penalty to copy the array and lesser performance operations do use more CPU and therefore more battery. I think you assumed that I was saying that it is a better solution, which I was not. I was making sure people have all of the information available to make an informed choice. Jun 15, 2020 at 18:07
-
1Yep, you're correct, there's no question inout is more efficient. I thought you were suggesting that
inout
is universally better because it saves battery. To which I'd say the readability, immutability, and thread safety of this solution are universally better and that inout should only be used as an optimization in those rare cases where the use case warrants it.– ToddHJun 16, 2020 at 19:33
use a NSMutableArray
or a NSArray
, which are classes
this way you don't need to implment any wraper and can use the build in bridging
open class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration
Based off of GoZoner's BoxedArray
answer, I created the class below that worked for me. I like the freedom of passing around arrays as references (as the other languages I work with do).
class MArray<T> : MutableCollection {
var array : Array<T> = Array()
var count: Int { return array.count } // getter (without, index func below will be called repeatedly to determine)
func add(_ value: T) {
array.append(value)
}
// MutableCollection requires:
subscript (index: Int) -> T {
get { return array[index] }
set(value) { array[index] = value }
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return array.count
}
func index(after i: Int) -> Int {
return i+1
}
}
account
a global variable and defining thechats
property ofChatsViewController
as:var chats: [Chat] { return account.chats }
.var chats: [Chat] { get { return account.chats } set { account.chats = newValue } }