Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a mutable array from a function

Tags:

swift

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!

like image 324
Damien Avatar asked Jun 08 '14 18:06

Damien


1 Answers

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.

like image 183
drewag Avatar answered Jan 02 '23 11:01

drewag