removeObjectsAtIndexes for Swift arrays

前端 未结 14 1182
长情又很酷
长情又很酷 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:00

    Updated for Swift 2.0:

    extension Array {
        mutating func removeAtIndices(incs: [Int]) {
            incs.sort(>).map { removeAtIndex($0) }
        }
    }
    

    Use forEach instead of map if it gives a warning that the result isn't used (Since Swift 2 beta 6 I think)

    EDIT: Super generic lazy solution:

    extension RangeReplaceableCollectionType where Index : Comparable {
        mutating func removeAtIndices(indices: S) {
            indices.sort().lazy.reverse().forEach{ removeAtIndex($0) }
        }
    }
    

提交回复
热议问题