iOS swift从另一个数组中删除数组的元素

Dev*_*mak 56 arrays ios swift

我有两个数组

var array1 = new Array ["a", "b", "c", "d", "e"]
var array2 = new Array ["a", "c", "d"]
Run Code Online (Sandbox Code Playgroud)

我想从array1中删除array2的元素

Result ["b", "e"]
Run Code Online (Sandbox Code Playgroud)

jrc*_*jrc 81

@ 安东尼奥的解决方案是更好的性能,但这种保留排序,如果这是很重要的:

var array1 = ["a", "b", "c", "d", "e"]
let array2 = ["a", "c", "d"]
array1 = array1.filter { !array2.contains($0) }
Run Code Online (Sandbox Code Playgroud)

  • 为了使其工作,您的对象还必须符合Equatable协议.如果没有,你会在Swift 4.0中得到这个奇怪的错误:在过滤器内的contains函数中调用缺少参数标签'where:'. (4认同)
  • @ c1pherB1t是的,您可以在“ contains”中添加`where:`,即```array1 = array1.filter({item in!array2.contains(where:{$ 0.id == item.id})}) ``` (3认同)
  • 如果元素是"Hashable",就像它们在这种情况下那样,将"array2"首先转换为"Set"可能会更高效.这仍然会保留顺序,因为`array1`仍然是一个数组,但您可以对搜索集合执行快速查找. (2认同)

Ant*_*nio 57

最简单的方法是将两个数组转换为集合,从第一个数组中减去第二个数组,将结果转换为数组并将其分配回array1:

array1 = Array(Set(array1).subtracting(array2))
Run Code Online (Sandbox Code Playgroud)

请注意,您的代码无效Swift - 您可以使用类型推断来声明和初始化两个数组,如下所示:

var array1 = ["a", "b", "c", "d", "e"]
var array2 = ["a", "c", "d"]
Run Code Online (Sandbox Code Playgroud)

  • 这真的很好 - 它似乎也尊重原始订单 - 总能得到保证吗? (4认同)
  • 不保证顺序: > 唯一元素的无序集合。https://developer.apple.com/documentation/swift/set (2认同)

Kru*_*nal 8

使用索引数组删除元素:

  1. 字符串和索引的数组

    let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
    let indexAnimals = [0, 3, 4]
    let arrayRemainingAnimals = animals
        .enumerated()
        .filter { !indexAnimals.contains($0.offset) }
        .map { $0.element }
    
    print(arrayRemainingAnimals)
    
    //result - ["dogs", "chimps", "cow"]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 整数和索引的数组

    var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    let indexesToRemove = [3, 5, 8, 12]
    
    numbers = numbers
        .enumerated()
        .filter { !indexesToRemove.contains($0.offset) }
        .map { $0.element }
    
    print(numbers)
    
    //result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
    
    Run Code Online (Sandbox Code Playgroud)



使用另一个数组的元素值删除元素

  1. 整数数组

    let arrayResult = numbers.filter { element in
        return !indexesToRemove.contains(element)
    }
    print(arrayResult)
    
    //result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 字符串数组

    let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
    let arrayRemoveLetters = ["a", "e", "g", "h"]
    let arrayRemainingLetters = arrayLetters.filter {
        !arrayRemoveLetters.contains($0)
    }
    
    print(arrayRemainingLetters)
    
    //result - ["b", "c", "d", "f", "i"]
    
    Run Code Online (Sandbox Code Playgroud)