如何在苹果的新语言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)
}

其他回答

从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+中工作,并且在写这篇文章时是测试版。

Swift中很少涉及数组操作

创建数组

var stringArray = ["One", "Two", "Three", "Four"]

在数组中添加对象

stringArray = stringArray + ["Five"]

从索引对象中获取值

let x = stringArray[1]

添加对象

stringArray.append("At last position")

在索引处插入对象

stringArray.insert("Going", at: 1)

删除对象

stringArray.remove(at: 3)

Concat对象值

var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"

这应该做到(未测试):

animals[2...3] = []

编辑:你需要让它成为一个var,而不是let,否则它是一个不可变的常数。

要从数组中删除元素,使用remove(at:), removeLast()和removeAll()。

yourArray = [1,2,3,4]

删除2位置的值

yourArray.remove(at: 2)

从数组中移除最后一个值

yourArray.removeLast()

从集合中移除所有成员

yourArray.removeAll()

你可以这么做。首先确保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)!)
        }
    }
}