阵列扩展通过值删除对象 [英] Array extension to remove object by value

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

问题描述

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

不过,我得到关于 VAR指数=发现(个体经营,对象)

'T'是无法转换为'T'

'T' is not convertible to 'T'

我也试过用这种方法签名: FUNC的removeObject(对象: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?

推荐答案

由于 2斯威夫特,这可以用实现的协议扩展方法的。
的removeObject()被定义为符合所有类型的方法
RangeReplaceableCollectionType (特别是关于阵列),如果
集合的元素是 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]

更新雨燕2 / X code 7测试版2:空速速度注意到
评价,现在实际上是可能写在一个通用的类型是模板上更严格的方法,因此该方法
可现在居然被定义为阵列的扩展

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.

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

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