如何在苹果的新语言Swift中取消设置/删除数组中的元素?
下面是一些代码:
let animals = ["cats", "dogs", "chimps", "moose"]
如何将元素animals[2]从数组中移除?
如何在苹果的新语言Swift中取消设置/删除数组中的元素?
下面是一些代码:
let animals = ["cats", "dogs", "chimps", "moose"]
如何将元素animals[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块来设置一个“打破”循环的标志,从而重新工作以删除“所有”红色汽车。
其他回答
从Xcode 10+开始,根据WWDC 2018会议223“包含算法”,一个好的方法将是mutmutingfunc removeAll(where predicate: (Element) throws -> Bool)重新抛出
苹果的例子:
var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."
请参阅Apple的文档
所以在OP的例子中,移除动物[2],“黑猩猩”:
var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeAll(where: { $0 == "chimps" } )
// or animals.removeAll { $0 == "chimps" }
这种方法可能是首选的,因为它的伸缩性很好(线性vs二次),可读和干净。请记住,它只能在Xcode 10+中工作,并且在写这篇文章时是测试版。
let关键字用于声明不能更改的常量。如果你想修改一个变量,你应该使用var代替,例如:
var animals = ["cats", "dogs", "chimps", "moose"]
animals.remove(at: 2) //["cats", "dogs", "moose"]
一个保持原始集合不变的非突变替代方法是使用过滤器创建一个新的集合,而不删除你想要的元素,例如:
let pets = animals.filter { $0 != "chimps" }
要从数组中删除元素,使用remove(at:), removeLast()和removeAll()。
yourArray = [1,2,3,4]
删除2位置的值
yourArray.remove(at: 2)
从数组中移除最后一个值
yourArray.removeLast()
从集合中移除所有成员
yourArray.removeAll()
斯威夫特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]
Swift4:
list = list.filter{$0 != "your Value"}