Array+SectionModel.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // Array+SectionModel.swift
  3. // SwiftBilibili
  4. //
  5. // Created by 罗文 on 2021/1/13.
  6. // Copyright © 2021年 罗文. All rights reserved.
  7. //
  8. import RxDataSources
  9. extension Array where Element: SectionModelType {
  10. subscript(indexPath: IndexPath) -> Element.Item {
  11. get {
  12. return self[indexPath.section].items[indexPath.item]
  13. }
  14. mutating set {
  15. self.update(section: indexPath.section) { items in
  16. items[indexPath.item] = newValue
  17. }
  18. }
  19. }
  20. mutating func insert(newElement: Element.Item, at indexPath: IndexPath) {
  21. self.update(section: indexPath.section) { items in
  22. items.insert(newElement, at: indexPath.item)
  23. }
  24. }
  25. @discardableResult
  26. mutating func remove(at indexPath: IndexPath) -> Element.Item {
  27. return self.update(section: indexPath.section) { items in
  28. return items.remove(at: indexPath.item)
  29. }
  30. }
  31. mutating func replace(section: Int, items: [Element.Item]) {
  32. self[section] = Element.init(original: self[section], items: items)
  33. }
  34. private mutating func update<T>(section: Int, mutate: (inout [Element.Item]) -> T) -> T {
  35. var items = self[section].items
  36. let value = mutate(&items)
  37. self[section] = Element.init(original: self[section], items: items)
  38. return value
  39. }
  40. }