How to remove multiple items from a swift array?

后端 未结 3 1518
孤城傲影
孤城傲影 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条回答
  • 2021-02-12 18:17

    Swift 3: Use swift closure to perform the same operation.

    If your array is like

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

    and indexes you want to remove

    let indexesToBeRemoved: Set = [2, 4]
    
    numbers = numbers
        .enumerated()
        .filter { !indexesToRemove.contains($0.offset) }
        .map { $0.element }
    and result
    

    print(numbers) // [0, 1, 3, 5]

    Swift 3: Here is same operation with JSON Object (dictionary)

    var arrayString = [
        [ "char" : "Z" ],
        [ "char" : "Y" ],
        [ "char" : "X" ],
        [ "char" : "W" ],
        [ "char" : "V" ],
        [ "char" : "U" ],
        [ "char" : "T" ],
        [ "char" : "S" ]
    ]
    
    let arrayIndex = [2, 3, 5]
    
    arrayString = arrayString.enumerated()
        .filter { !arrayIndex.contains($0.0 + 1) }
        .map { $0.1 }
    
    print(arrayString)
    

    [["char": "Z"], ["char": "W"], ["char": "U"], ["name": "T"], ["name": "S"]]

    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2021-02-12 18:26

    It's simple. delete items from the end.

    First delete 3 and after that delete 1

    0 讨论(0)
提交回复
热议问题