如何在苹果的新语言Swift中取消设置/删除数组中的元素?

下面是一些代码:

let animals = ["cats", "dogs", "chimps", "moose"]

如何将元素animals[2]从数组中移除?


当前回答

如果你有一个自定义对象数组,你可以像这样通过特定的属性进行搜索:

if let index = doctorsInArea.firstIndex(where: {$0.id == doctor.id}){
    doctorsInArea.remove(at: index)
}

或者如果你想通过名字来搜索

if let index = doctorsInArea.firstIndex(where: {$0.name == doctor.name}){
    doctorsInArea.remove(at: index)
}

其他回答

Swift4:

list = list.filter{$0 != "your Value"}

斯威夫特5

guard let index = orders.firstIndex(of: videoID) else { return }
orders.remove(at: index)

鉴于

var animals = ["cats", "dogs", "chimps", "moose"]

删除第一个元素

animals.removeFirst() // "cats"
print(animals)        // ["dogs", "chimps", "moose"]

删除最后一个元素

animals.removeLast() // "moose"
print(animals)       // ["cats", "dogs", "chimps"]

删除索引处的元素

animals.remove(at: 2) // "chimps"
print(animals)           // ["cats", "dogs", "moose"]

删除未知索引的元素

只针对一个元素

if let index = animals.firstIndex(of: "chimps") {
    animals.remove(at: index)
}
print(animals) // ["cats", "dogs", "moose"]

对于多个元素

var animals = ["cats", "dogs", "chimps", "moose", "chimps"]

animals = animals.filter(){$0 != "chimps"}
print(animals) // ["cats", "dogs", "moose"]

笔记

上述方法就地修改数组(过滤器除外)并返回被删除的元素。 快速指南地图滤镜减少 如果不想修改原始数组,可以使用dropFirst或dropLast创建一个新数组。

更新至Swift 5.2

使用索引数组删除元素:

Array of Strings and indexes 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"] Array of Integers and indexes 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]

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

整数数组 let arrayResult = numbers。筛选器{元素 返回! indexesToRemove.contains(元素) } 打印(arrayResult) //result - [0,1,2,4,6,7,9,10,11] 字符串数组 让arrayLetters =(“a”、“b”、“c”,“d”,“e”,“f”,“g”,“h”,“我”) let arrayRemoveLetters = ["a", "e", "g", "h"] let arrayRemainingLetters = arrayLetters。过滤器{ ! arrayRemoveLetters.contains (0) } 打印(arrayRemainingLetters) //result - ["b", "c", "d", "f", "i"]

let关键字用于声明不能更改的常量。如果你想修改一个变量,你应该使用var代替,例如:

var animals = ["cats", "dogs", "chimps", "moose"]

animals.remove(at: 2)  //["cats", "dogs", "moose"]

一个保持原始集合不变的非突变替代方法是使用过滤器创建一个新的集合,而不删除你想要的元素,例如:

let pets = animals.filter { $0 != "chimps" }