数组扩展以按值删除对象 [英] Array extension to remove object by value

查看:23
本文介绍了数组扩展以按值删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

extension Array {
    func removeObject<T where T : Equatable>(object: T) {
        var index = find(self, object)
        self.removeAtIndex(index)
    }
}

但是,我在 var index = find(self, object)

'T' 不能转换为 'T'

'T' is not convertible to 'T'

我也尝试过这个方法签名:func removeObject(object: AnyObject),但是,我得到了同样的错误:

I also tried with this method signature: func removeObject(object: AnyObject), however, I get the same error:

'AnyObject' 不能转换为 'T'

'AnyObject' is not convertible to 'T'

这样做的正确方法是什么?

What is the proper way to do this?

推荐答案

Swift 2 开始,这可以通过协议扩展方法来实现.removeObject() 被定义为所有符合类型的方法到 RangeReplaceableCollectionType(特别是在 Array 上)如果集合的元素是 Equatable:

As of Swift 2, this can be achieved with a protocol extension method. removeObject() is defined as a method on all types conforming to RangeReplaceableCollectionType (in particular on Array) if the elements of the collection are Equatable:

extension RangeReplaceableCollectionType where Generator.Element : Equatable {

    // Remove first collection element that is equal to the given `object`:
    mutating func removeObject(object : Generator.Element) {
        if let index = self.indexOf(object) {
            self.removeAtIndex(index)
        }
    }
}

示例:

var ar = [1, 2, 3, 2]
ar.removeObject(2)
print(ar) // [1, 3, 2]

Swift 2/Xcode 7 beta 2 的更新: 正如 Airspeed Velocity 所注意到的在评论中,现在实际上可以在对模板有更多限制的泛型类型上编写方法,因此该方法现在实际上可以定义为 Array 的扩展:

Update for Swift 2 / Xcode 7 beta 2: As Airspeed Velocity noticed in the comments, it is now actually possible to write a method on a generic type that is more restrictive on the template, so the method could now actually be defined as an extension of Array:

extension Array where Element : Equatable {

    // ... same method as above ...
}

协议扩展仍然具有适用于更大的一组类型.

The protocol extension still has the advantage of being applicable to a larger set of types.

Swift 3 的更新:

extension Array where Element: Equatable {

    // Remove first collection element that is equal to the given `object`:
    mutating func remove(object: Element) {
        if let index = index(of: object) {
            remove(at: index)
        }
    }
}

这篇关于数组扩展以按值删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆