Guest User

Untitled

a guest
Mar 20th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. import Foundation
  2.  
  3. protocol DateElement {
  4. var dateKey: Date {get set}
  5. }
  6.  
  7. protocol DateSection : DateElement {
  8. associatedtype Element: DateElement, Equatable
  9. var elements: [Element] {get set}
  10. }
  11.  
  12. // 分区类型
  13. public enum SplitType : Int {
  14. case none // 不分区
  15. case day // 按天分区
  16. case month // 按月分区
  17. case year // 按年分区
  18.  
  19. func formatterStr() -> String {
  20. switch self {
  21. case .day:
  22. return "yyyyMMdd"
  23. case .month:
  24. return "yyyyMM"
  25. case .year:
  26. return "yyyy"
  27. case .none:
  28. return "yyyyMMddHHmmss"
  29. }
  30. }
  31.  
  32. func name(_ date: Date) -> String {
  33. return (date as NSDate).str(withFormatterStr: formatterStr())
  34. }
  35.  
  36. func date(_ name: String) -> Date {
  37. return NSDate.init(fromStr: name, formatterStr: formatterStr())! as Date
  38. }
  39. }
  40.  
  41. extension Array where Element: DateSection {
  42. /// 添加新的元素数组,进行分区。增量操作
  43. ///
  44. /// - Parameters:
  45. /// - list: 新的元素数组
  46. /// - createSection: 分区的Section的构造方法 (PS:就是创建一个新的DateSection的方法,如果有更好的直接通过DateSection 协议实现,希望可以comment)
  47. /// - type: 分区类型
  48. mutating func add(newList list:[Element.Element], createSection: ()->Element, splitType type: SplitType = .none) {
  49.  
  50. // 是否需要分区
  51. let shouldSplit = (type != .none)
  52.  
  53. self = list.reduce(into: self) { (result, item) in
  54. let itemDateName = type.name(item.dateKey)
  55. var filter = result
  56. if shouldSplit {
  57. // 这里filter出来的数据不是拷贝,可以直接修改原数据,good
  58. filter = result.filter({ (section) -> Bool in
  59. type.name(section.dateKey) == itemDateName
  60. })
  61. }
  62.  
  63. var existSection = filter.first
  64. if existSection == nil {
  65. // 这里需要创建一个 Element类型的实例
  66. existSection = createSection()
  67. result.append(existSection!)
  68. if shouldSplit {
  69. existSection?.dateKey = item.dateKey
  70. result.sortByDate()
  71. }
  72. }
  73. if !existSection!.elements.contains{ $0 == item} {
  74. existSection!.elements.append(item)
  75. existSection!.elements.sortByDate()
  76. }
  77. }
  78. }
  79.  
  80.  
  81. }
  82.  
  83. extension Array where Element: DateElement {
  84. mutating func sortByDate() {
  85. self.sort(by: { (left, right) -> Bool in
  86. let ret = left.dateKey.compare(right.dateKey)
  87. return (ret == ComparisonResult.orderedAscending ? false : true)
  88. })
  89. }
  90. }
Add Comment
Please, Sign In to add comment