如何在苹果的新语言Swift中取消设置/删除数组中的元素?
下面是一些代码:
let animals = ["cats", "dogs", "chimps", "moose"]
如何将元素animals[2]从数组中移除?
如何在苹果的新语言Swift中取消设置/删除数组中的元素?
下面是一些代码:
let animals = ["cats", "dogs", "chimps", "moose"]
如何将元素animals[2]从数组中移除?
当前回答
我提出了以下扩展,负责从数组中删除元素,假设数组中的元素实现了Equatable:
extension Array where Element: Equatable {
mutating func removeEqualItems(_ item: Element) {
self = self.filter { (currentItem: Element) -> Bool in
return currentItem != item
}
}
mutating func removeFirstEqualItem(_ item: Element) {
guard var currentItem = self.first else { return }
var index = 0
while currentItem != item {
index += 1
currentItem = self[index]
}
self.remove(at: index)
}
}
用法:
var test1 = [1, 2, 1, 2]
test1.removeEqualItems(2) // [1, 1]
var test2 = [1, 2, 1, 2]
test2.removeFirstEqualItem(2) // [1, 1, 2]
其他回答
上面的答案似乎假定您知道要删除的元素的索引。
通常,您知道对数组中要删除的对象的引用。在这种情况下,直接使用对象引用可能会更容易,而不必到处传递它的索引。因此,我建议这个解决方案。它使用标识符!==,用于测试两个对象引用是否都引用同一个对象实例。
func delete(element: String) {
list = list.filter { $0 != element }
}
当然,这不仅仅适用于字符串。
你可以这么做。首先确保Dog确实存在于数组中,然后删除它。如果您认为Dog可能在数组中发生多次,则添加for语句。
var animals = ["Dog", "Cat", "Mouse", "Dog"]
let animalToRemove = "Dog"
for object in animals {
if object == animalToRemove {
animals.remove(at: animals.firstIndex(of: animalToRemove)!)
}
}
如果你确定Dog在数组中退出并且只发生了一次,那么就这样做:
animals.remove(at: animals.firstIndex(of: animalToRemove)!)
如果两者都有,字符串和数字
var array = [12, 23, "Dog", 78, 23]
let numberToRemove = 23
let animalToRemove = "Dog"
for object in array {
if object is Int {
// this will deal with integer. You can change to Float, Bool, etc...
if object == numberToRemove {
array.remove(at: array.firstIndex(of: numberToRemove)!)
}
}
if object is String {
// this will deal with strings
if object == animalToRemove {
array.remove(at: array.firstIndex(of: animalToRemove)!)
}
}
}
使用索引数组删除元素:
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"]
扩展删除字符串对象
extension Array {
mutating func delete(element: String) {
self = self.filter() { $0 as! String != element }
}
}
这应该做到(未测试):
animals[2...3] = []
编辑:你需要让它成为一个var,而不是let,否则它是一个不可变的常数。