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

下面是一些代码:

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

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


当前回答

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])"

其他回答

上面的答案似乎假定您知道要删除的元素的索引。

通常,您知道对数组中要删除的对象的引用。在这种情况下,直接使用对象引用可能会更容易,而不必到处传递它的索引。因此,我建议这个解决方案。它使用标识符!==,用于测试两个对象引用是否都引用同一个对象实例。

func delete(element: String) {
    list = list.filter { $0 != element }
}

当然,这不仅仅适用于字符串。

我使用这个扩展,几乎与Varun的一样,但这一个(下面)是万能的:

 extension Array where Element: Equatable  {
        mutating func delete(element: Iterator.Element) {
                self = self.filter{$0 != element }
        }
    }

使用索引数组删除元素:

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"]

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

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

yourArray = [1,2,3,4]

删除2位置的值

yourArray.remove(at: 2)

从数组中移除最后一个值

yourArray.removeLast()

从集合中移除所有成员

yourArray.removeAll()