如何在苹果的新语言Swift中取消设置/删除数组中的元素?
下面是一些代码:
let animals = ["cats", "dogs", "chimps", "moose"]
如何将元素animals[2]从数组中移除?
如何在苹果的新语言Swift中取消设置/删除数组中的元素?
下面是一些代码:
let animals = ["cats", "dogs", "chimps", "moose"]
如何将元素animals[2]从数组中移除?
当前回答
如果你不知道你想要删除的元素的索引,并且元素符合Equatable协议,你可以这样做:
animals.remove(at: animals.firstIndex(of: "dogs")!)
参见Equatable协议答案:我如何做indexOfObject或一个适当的containsObject
其他回答
斯威夫特5: 这是一个很酷的和简单的扩展来删除数组中的元素,而不需要过滤:
extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(object: Element) {
guard let index = firstIndex(of: object) else {return}
remove(at: index)
}
}
用法:
var myArray = ["cat", "barbecue", "pancake", "frog"]
let objectToRemove = "cat"
myArray.remove(object: objectToRemove) // ["barbecue", "pancake", "frog"]
也适用于其他类型,例如Int,因为Element是泛型类型:
var myArray = [4, 8, 17, 6, 2]
let objectToRemove = 17
myArray.remove(object: objectToRemove) // [4, 8, 6, 2]
关于@Suragch的替代方案“删除未知索引的元素”:
“indexOf(element)”有一个更强大的版本,它将匹配谓词而不是对象本身。它使用相同的名称,但它被myObjects.indexOf{$0调用。property = valueToMatch}。它返回myObjects数组中找到的第一个匹配项的索引。
如果元素是一个对象/结构,您可能希望根据其属性之一的值删除该元素。例如,你有一个Car类拥有Car。color属性,你想从carsArray中删除“红色”汽车。
if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
carsArray.removeAtIndex(validIndex)
}
可以预见的是,您可以通过在repeat/while循环中嵌入上述if语句,并附加一个else块来设置一个“打破”循环的标志,从而重新工作以删除“所有”红色汽车。
你可以这么做。首先确保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)!)
}
}
}
let关键字用于声明不能更改的常量。如果你想修改一个变量,你应该使用var代替,例如:
var animals = ["cats", "dogs", "chimps", "moose"]
animals.remove(at: 2) //["cats", "dogs", "moose"]
一个保持原始集合不变的非突变替代方法是使用过滤器创建一个新的集合,而不删除你想要的元素,例如:
let pets = animals.filter { $0 != "chimps" }
斯威夫特5
guard let index = orders.firstIndex(of: videoID) else { return }
orders.remove(at: index)