3 回答
TA贡献1812条经验 获得超5个赞
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]
Array
:
extension Array where Element : Equatable { // ... same method as above ...}
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) } }}
TA贡献1811条经验 获得超4个赞
注
'T' is not convertible to 'T'
'AnyObject' is not convertible to 'T'
func removeObject<T : Equatable>(object: T, inout fromArray array: [T]) {}
func arrayRemovingObject<T : Equatable>(object: T, fromArray array: [T]) -> [T] {}
extension Array { mutating func removeObject<U: Equatable>(object: U) { var index: Int? for (idx, objectToCompare) in enumerate(self) { if let to = objectToCompare as? U { if object == to { index = idx } } } if(index != nil) { self.removeAtIndex(index!) } }}var list = [1,2,3]list.removeObject(2) // Successfully removes 2 because types matchedlist.removeObject("3") // fails silently to remove anything because the types don't matchlist // [1, 3]
编辑
extension Array { mutating func removeObject<U: Equatable>(object: U) -> Bool { for (idx, objectToCompare) in self.enumerate() { //in old swift use enumerate(self) if let to = objectToCompare as? U { if object == to { self.removeAtIndex(idx) return true } } } return false }}var list = [1,2,3,2]list.removeObject(2)list list.removeObject(2)list
TA贡献1911条经验 获得超7个赞
func removeObject<T : Equatable>(object: T, inout fromArray array: [T]) { var index = find(array, object) array.removeAtIndex(index!)}
- 3 回答
- 0 关注
- 557 浏览
添加回答
举报