如何从函数返回一个可变数组?
这是一段简短的代码片段,使其更加清晰:
- 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'
以下代码片段有效但我必须返回一个数组,而不是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"]
谢谢!