Reputation: 27473
How to return a mutable array from a function?
Here is a short snippet of code to make it more clear:
var tasks = ["Mow the lawn", "Call Mom"]
var completedTasks = ["Bake a cake"]
func arrayAtIndex(index: Int) -> String[] {
if index == 0 {
return tasks
} else {
return completedTasks
}
}
arrayAtIndex(0).removeAtIndex(0)
// Immutable value of type 'String[]' only has mutating members named 'removeAtIndex'
The following snippet works but I have to return an Array
, not an NSMutableArray
var tasks: NSMutableArray = ["Mow the lawn", "Call Mom"]
var completedTasks: NSMutableArray = ["Bake a cake"]
func arrayAtIndex(index: Int) -> NSMutableArray {
if index == 0 {
return tasks
} else {
return completedTasks
}
}
arrayAtIndex(0).removeObjectAtIndex(0)
tasks // ["Call Mom"]
Thanks!
Upvotes: 9
Views: 14918
Reputation: 94723
This whole paradigm is discouraged in Swift. Arrays in swift are "Value Types" meaning that they get copied every time they are passed around. This means that once you pass the array into a function, you cannot have that function modify the contents of the original array. This is much safer.
What you could do is:
var newArray = arrayAtIndex(0)
newArray.removeObjectAtIndex(0)
But note that tasks
will not be modified. NewArray
will be a copy of tasks
with the first object removed
The reason this works with NSMutableArray, is that NSArray and NSMutableArray are copied by reference, so they always refer to the original array unless explicitly copied.
Upvotes: 3