gpt4 book ai didi

ios - 数组扩展以按值删除对象

转载 作者:行者123 更新时间:2023-11-30 14:19:33 24 4
gpt4 key购买 nike

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

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

上收到错误

'T' is not convertible to 'T'

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

'AnyObject' is not convertible to 'T'

执行此操作的正确方法是什么?

最佳答案

Swift 2 开始,这可以通过协议(protocol)扩展方法来实现。removeObject() 被定义为所有符合条件的类型的方法到 RangeReplaceableCollectionType (特别是在 Array 上)如果集合的元素是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 的扩展:

extension Array where Element : Equatable {

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

协议(protocol)扩展仍然具有适用于更大的类型集。

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)
}
}
}

Swift 5 更新:

extension Array where Element: Equatable {

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

关于ios - 数组扩展以按值删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30658555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com