7
如何從函數返回可變數組?從函數返回可變數組
下面是一小段代碼,使之更加明確:
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'
下面的代碼片段的作品,但我不得不返回Array
,不是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"]
謝謝!
感謝您的回答,這是完全合理的。然而,值得注意的是,在整個程序中,'tasks'和'completedTasks'是實例變量(用'var'聲明),並且我返回'self.tasks'和'self.completedTasks'。我無法複製返回的數組,刪除一個元素,然後重新分配實例變量,因爲實例變量本身被轉換爲不可變。實例變量在被函數返回後可能如何轉換爲不可變的? – Damien