Returning a modified array from a function

How to return a changed array from a function?

Here is a short code snippet to make it clearer:

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 Array , not 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!

+7
swift
source share
1 answer

This whole paradigm is not encouraged in Swift. Arrays in swift are Value Types, which means they are copied every time they are passed. This means that once you pass an array to a function, you cannot change this function in the original array. It is much safer.

What can you do:

 var newArray = arrayAtIndex(0) newArray.removeObjectAtIndex(0) 

But note that tasks will not be changed. NewArray will be a copy of tasks with the first object deleted

The reason this works with NSMutableArray is because NSArray and NSMutableArray are copied by reference, so they always refer to the original array unless explicitly copied.

+2
source share

All Articles