removeObjectsAtIndexes for Swift arrays

前端 未结 14 1194
长情又很酷
长情又很酷 2020-11-30 12:34

What is a Swift array equivalent to NSMutableArray\'s -removeObjectsAtIndexes:? Removing each index one by one doesn\'t work, as remaining indexes

14条回答
  •  一整个雨季
    2020-11-30 13:02

    I have not tested this, but I would bet that a non-mutating version is faster if it copies contiguous subranges. Something like:

    extension Array {
            public func removing(indices indicesToRemove: IndexSet) -> Self {
                guard let lastIndex = indicesToRemove.last else {
                    return self
                }
    
                assert(lastIndex <= (self.count - 1), message: "Index set contains out of bounds indices")
    
                var result = Self()
                result.reserveCapacity(self.count - indicesToRemove.count)
    
                let indicesToKeep = IndexSet(self.indices).subtracting(indicesToRemove)
                let rangesToKeep = indicesToKeep.rangeView
    
                rangesToKeep.forEach { (range) in
                    result.append(contentsOf: self[range])
                }
    
                return result
            }
    }
    

提交回复
热议问题