如何删除数组列表中数组的所有元素

时间:2020-10-28 04:22:56

标签: ios swift xcode

我有一个数组列表,如下所示:

var lists = [[Category]]()

“列表”中的每个元素代表一个对象数组(类别),我试图在使用它后重新初始化“列表”(清除每个元素)。

我的方法:

lists.forEach { list in 
    list.removeAll()
}

错误:由于“列表”是一个常量变量,因此无法对“列表”进行突变

反正我可以在Swift中实现目标吗?

5 个答案:

答案 0 :(得分:2)

由于数组是值类型,并且具有写时复制的语义,因此“清除数组的所有嵌套数组”与“使用空嵌套数组创建新数组的数量与旧嵌套数组一样多”是没有区别的阵列,然后将其重新分配到旧阵列。

所以你可以做

lists = Array(repeating: [], count: lists.count)

或者:

lists = lists.map { _ in [] }

从注释中看,您似乎正在编写一个清除所有嵌套数组的函数。在这种情况下,您需要一个inout参数:

func clearList(_ lists: inout [[Category]]) {
    lists = Array(repeating: [], count: lists.count)
}

并称之为:

var myLists = [listCate1, listCate2]
clearList(&myLists)
// myLists will be [[], []], note that this does not change listCate1 or listCate2

如果您真的希望函数使传入的任意数量的列表发生突变,则需要使用不安全的指针(非常不推荐):

func clearList(_ lists: UnsafeMutablePointer<[Category]>...) {
    for list in lists {
        list.pointee = []
    }
}

clearList(&listCate1, &listCate2)实际上会改变listCate1listCate2,但这是一个相当肮脏的把戏。

答案 1 :(得分:0)

您可以分配一个空数组文字,写为[](一对空的方括号)

lists = []

列表现在是一个空数组,但类型仍然为[[Category]]

答案 2 :(得分:0)

您可以删除数组的所有元素并保留容量。

lists.removeAll(keepingCapacity: true)

或者如果您想基于某些条件从数组中删除对象,则可以使用此...

lists.removeAll { (obj) -> Bool in

   if <check some condition {   return true  }
   else { false  }
   
 }

答案 3 :(得分:0)

    var someInts1 = [30,11,34]
    var someInts2 = [30,11,34]
    var someInts3 = [30,11,34]

    var lists = [Any]()
    lists = [someInts1, someInts2, someInts3]
    print(lists) // [[30,11,34], [30,11,34], [30,11,34]]

    lists = [] // this is where the list become empty
    print(lists) // []

答案 4 :(得分:0)

我将创建具有可变和不可变变体的扩展。通过扩展RangeReplaceableCollection而不是Array,我们不需要将Array.Element限制为任何特定类型。

extension RangeReplaceableCollection where Element: RangeReplaceableCollection {
    func stripped() -> Self {
        return .init(repeating: .init(), count: count)
    }

    mutating func strip() {
        self = stripped()
    }
}

现在,如果我们的数组被声明为可变的,则可以将其剥离:

var mutable: [[Category]] = []
mutable.strip()

或者我们可以对let常量使用不可变的变体:

let immutable: [[Category]] = []
let stripped = immutable.stripped()