ios 在 Swift 3 中从数组中删除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40859066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:52:13  来源:igfitidea点击:

Removing object from array in Swift 3

iosarraysswiftswift3

提问by Kamlesh Shingarakhiya

In my application I added one object in array when select cell and unselect and remove object when re-select cell. I used that code but give me error.

在我的应用程序中,我在选择单元格时在数组中添加了一个对象,在重新选择单元格时取消选择并删除对象。我使用了该代码,但给了我错误。

extension Array {
    func indexOfObject(object : AnyObject) -> NSInteger {
        return (self as NSArray).indexOfObject(object)
    }

    mutating func removeObject(object : AnyObject) {
        for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object) {
            self.removeAtIndex(index)
        }
    }
}

class MyViewController: UITableViewController {
    var arrContacts: [Any] = []
    var contacts: [Any] = []

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        arrContacts.removeObject(contacts[indexPath.row])
    }
}

It gives me 2 error like that:

它给了我 2 个这样的错误:

C-style for statement has been removed in Swift 3
Value of type '[Any]' has no member 'removeObject'

回答by vadian

The Swift equivalent to NSMutableArray's removeObjectis:

NSMutableArray's等效的 SwiftremoveObject是:

var array = ["alpha", "beta", "gamma"]

if let index = array.firstIndex(of: "beta") {
    array.remove(at: index)
}

if the objects are unique. There is no need at all to cast to NSArrayand use indexOfObject:

如果对象是唯一的。根本不需要投射NSArray和使用indexOfObject:

The API index(of:also works but this causes an unnecessary implicit bridge cast to NSArray.

APIindex(of:也可以工作,但这会导致不必要的隐式桥转换为NSArray.

If there are multiple occurrences of the same object use filter. However in cases like data source arrays where an index is associated with a particular object firstIndex(ofis preferable because it's faster than filter.

如果同一对象多次出现,请使用filter. 但是,在索引与特定对象相关联的数据源数组之类的情况下firstIndex(of,它更可取,因为它比filter.

Update:

更新:

In Swift 4.2+ you can remove one or multiple occurrences of betawith removeAll(where:):

在 Swift 4.2+ 中,您可以删除一次或多次出现的betawith removeAll(where:)

array.removeAll{
var a = ["one", "two", "three", "four", "five"]

// Remove/filter item with value 'three'
a = a.filter { 
var array = ["alpha", "beta", "gamma"]
if let index = array.index(where: {
extension Array where Element: Equatable {

    @discardableResult mutating func remove(object: Element) -> Bool {
        if let index = index(of: object) {
            self.remove(at: index)
            return true
        }
        return false
    }

    @discardableResult mutating func remove(where predicate: (Array.Iterator.Element) -> Bool) -> Bool {
        if let index = self.index(where: { (element) -> Bool in
            return predicate(element)
        }) {
            self.remove(at: index)
            return true
        }
        return false
    }

}
== "beta"}) { array.remove(at: index) }
!= "three" }
== "beta"}

回答by nyxee

let obj1 = MyObject(id: 1)
let obj2 = MyObject(id: 2)
var array: [MyObject] = [obj1, obj2]

array.remove(where: { (obj) -> Bool in
    return obj.id == 1
})
// OR
array.remove(object: obj2) 

回答by Mark Semsel

For Swift 3, you can use index(where:) and include a closure that does the comparison of an object in the array ($0) with whatever you are looking for.

对于 Swift 3,您可以使用 index(where:) 并包含一个闭包,该闭包将数组 ($0) 中的对象与您要查找的对象进行比较。

extension Array where Element: Equatable{
    mutating func remove (element: Element) {
        if let i = self.firstIndex(of: element) {
            self.remove(at: i)
        }
    }
}

回答by Luca Davanzo

Another nice and useful solution is to create this kind of extension:

另一个不错且有用的解决方案是创建这种扩展:

var array = ["alpha", "beta", "gamma"]
array.remove(element: "beta")

In this way, if you have your array with custom objects:

这样,如果您的数组包含自定义对象:

extension Array where Element: Equatable{
    mutating func remove (element: Element) {
        if let i = self.index(of: element) {
            self.remove(at: i)
        }
    }
}

回答by Mohsenasm

In Swift 5, Use this Extension:

Swift 5 中,使用这个Extension

var array = ["alpha", "beta", "gamma"]
array.remove(element: "beta")

example:

例子:

let indexes = arrContacts.enumerated().filter { 
let indexes = arrContacts.enumerated().filter { 
var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]

if let index = students.firstIndex(where: { 
if let index = array.enumerated().filter( { 
array.remove(at: Index)
.element === objectToRemove }).map({
array.removeAtIndex(index)
.offset }).first { array.remove(at: index) }
.hasPrefix("A") }) { students.remove(at: index) }
.element == contacts[indexPath.row] }.map{
"Declaration is only valid at file scope".
.offset } for index in indexes.reversed() { arrContacts.remove(at: index) }
.element == contacts[indexPath.row] }.map{
public extension Array where Element: Equatable {
    @discardableResult
    public mutating func remove(_ item: Element) -> Array {
        if let index = firstIndex(where: { item == ##代码## }) {
            remove(at: index)
        }
        return self
    }

    @discardableResult
    public mutating func removeAll(_ item: Element) -> Array {
        removeAll(where: { item == ##代码## })
        return self
    }
}
.offset } for index in indexes.reversed() { arrContacts.remove(at: index) }


In Swift 3, Use this Extension:

Swift 3 中,使用这个Extension

##代码##

example:

例子:

##代码##

回答by Tj3n

  1. for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object)is for loop in C-style and has been removed

  2. Change your code to something like this to remove all similar object if it have looped:

    ##代码##
  1. for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object)是 C 风格的 for 循环,已被删除

  2. 将您的代码更改为类似的内容以删除所有类似的对象(如果它已循环):

    ##代码##

回答by Sergey Di

Swift 4

斯威夫特 4

##代码##

回答by Joerg

The correct and working one-line solution for deleting a unique object (named "objectToRemove") from an array of these objects (named "array") in Swift 3 is:

在 Swift 3 中从这些对象(名为“array”)的数组中删除唯一对象(名为“objectToRemove”)的正确且有效的单行解决方案是:

##代码##

回答by Dili

Try this in Swift 3

在 Swift 3 中试试这个

##代码##

Instead of

代替

##代码##

Update

更新

##代码##

Make sure the object is in scope. You can give scope "internal", which is default.

确保对象在范围内。你可以给范围“内部”,这是默认的。

index(of:<Object>)to work, class should conform to Equatable

index(of:<Object>)工作,班级应符合 Equatable

回答by Renetik

Extension for array to do it easily and allow chaining for Swift 4.2 and up:

扩展数组以轻松完成并允许链接 Swift 4.2 及更高版本:

##代码##