Guest User

Untitled

a guest
Feb 25th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. import Foundation
  2.  
  3. extension Array {
  4.  
  5. /// move items at indices to index (insert them at index in the order of indices)
  6. ///
  7. /// could be useful for dragging and dropping in a table view
  8. ///
  9. /// - Parameters:
  10. /// - indices: the indices to move
  11. /// - index: the index to move them to
  12. mutating func move(indices: [Int], to index: Index) {
  13. var values: [Element] = []
  14. for i in indices {
  15. values.append(self[i])
  16. }
  17. // need to remove in reverse order so we don't change
  18. let sortedIndices = indices.sorted(by: >)
  19. for i in sortedIndices {
  20. self.remove(at: i)
  21. }
  22. // if we are removing elements before the index, then the insertion point needs to move backwards for each one
  23. var position = index - (indices.filter { $0 < index }).count
  24. for value in values {
  25. self.insert(value, at: position)
  26. position += 1
  27. }
  28. }
  29. }
  30.  
  31. var items = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
  32. items.move(indices: [7, 3, 5, 4], to: 2)
  33. print(items)
Add Comment
Please, Sign In to add comment