How to remove multiple items from a swift array?

后端 未结 3 1536
孤城傲影
孤城傲影 2021-02-12 17:56

For example i have an array

var array = [1, 2, 3, 4]

I want to remove item at index 1 then at index 3 \"let it be in a for loop\".

But

3条回答
  •  猫巷女王i
    2021-02-12 18:20

    Given your array

    var numbers = [1, 2, 3, 4]
    

    and a Set of indexes you want to remove

    let indexesToRemove: Set = [1, 3]
    

    You want to remove the values "2" and "4".

    Just write

    numbers = numbers
        .enumerated()
        .filter { !indexesToRemove.contains($0.offset) }
        .map { $0.element }
    

    Result

    print(numbers) // [1, 3]
    

提交回复
热议问题