Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- extension Array {
- /// move items at indices to index (insert them at index in the order of indices)
- ///
- /// could be useful for dragging and dropping in a table view
- ///
- /// - Parameters:
- /// - indices: the indices to move
- /// - index: the index to move them to
- mutating func move(indices: [Int], to index: Index) {
- var values: [Element] = []
- for i in indices {
- values.append(self[i])
- }
- // need to remove in reverse order so we don't change
- let sortedIndices = indices.sorted(by: >)
- for i in sortedIndices {
- self.remove(at: i)
- }
- // if we are removing elements before the index, then the insertion point needs to move backwards for each one
- var position = index - (indices.filter { $0 < index }).count
- for value in values {
- self.insert(value, at: position)
- position += 1
- }
- }
- }
- var items = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
- items.move(indices: [7, 3, 5, 4], to: 2)
- print(items)
Add Comment
Please, Sign In to add comment