Advertisement
shuklavatsal1992

Swift Array - Move element to position

Jul 20th, 2022
1,363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.98 KB | None | 0 0
  1. import Foundation
  2.  
  3. extension Array where Element: Equatable
  4. {
  5.     mutating func move(_ element: Element, to newIndex: Index) {
  6.         if let oldIndex: Int = self.firstIndex(of: element) { self.move(from: oldIndex, to: newIndex) }
  7.     }
  8. }
  9.  
  10. extension Array where Element == Dictionary<String, Any> {
  11.    
  12.     mutating func move(_ element:Element, to newIndex: Index) {
  13.         if let oldIndex = self.firstIndex(where: { ($0.keys.first ?? "") == (element.keys.first ?? "") }) {
  14.             self.move(from: oldIndex, to: newIndex)
  15.         }
  16.     }
  17. }
  18.  
  19. extension Array
  20. {
  21.     mutating func move(from oldIndex: Index, to newIndex: Index) {
  22.         // Don't work for free and use swap when indices are next to each other - this
  23.         // won't rebuild array and will be super efficient.
  24.         if oldIndex == newIndex { return }
  25.         if abs(newIndex - oldIndex) == 1 { return self.swapAt(oldIndex, newIndex) }
  26.         self.insert(self.remove(at: oldIndex), at: newIndex)
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement