Skip to content

Commit 11be1b6

Browse files
authored
Implement sort() and sort(by:) for IdentifiedArray. (#128)
1 parent c77bb6c commit 11be1b6

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

Sources/ComposableArchitecture/SwiftUI/IdentifiedArray.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,12 @@ where ID: Hashable {
184184
public mutating func move(fromOffsets source: IndexSet, toOffset destination: Int) {
185185
self.ids.move(fromOffsets: source, toOffset: destination)
186186
}
187+
188+
public mutating func sort(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows {
189+
try self.ids.sort {
190+
try areInIncreasingOrder(self.dictionary[$0]!, self.dictionary[$1]!)
191+
}
192+
}
187193
}
188194

189195
extension IdentifiedArray: CustomDebugStringConvertible {
@@ -220,6 +226,12 @@ extension IdentifiedArray: Equatable where Element: Equatable {}
220226

221227
extension IdentifiedArray: Hashable where Element: Hashable {}
222228

229+
extension IdentifiedArray where Element: Comparable {
230+
public mutating func sort() {
231+
sort(by: <)
232+
}
233+
}
234+
223235
extension IdentifiedArray: ExpressibleByArrayLiteral where Element: Identifiable, ID == Element.ID {
224236
public init(arrayLiteral elements: Element...) {
225237
self.init(elements)

Tests/ComposableArchitectureTests/IdentifiedArrayTests.swift

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,4 +149,50 @@ final class IdentifiedArrayTests: XCTestCase {
149149
]
150150
)
151151
}
152+
153+
struct ComparableValue: Comparable, Identifiable {
154+
let id: Int
155+
let value: Int
156+
157+
static func < (lhs: ComparableValue, rhs: ComparableValue) -> Bool {
158+
return lhs.value < rhs.value
159+
}
160+
}
161+
162+
func testSortBy() {
163+
var array: IdentifiedArray = [
164+
ComparableValue(id: 1, value: 100),
165+
ComparableValue(id: 2, value: 50),
166+
ComparableValue(id: 3, value: 75),
167+
]
168+
169+
array.sort { $0.value < $1.value }
170+
171+
XCTAssertEqual([2, 3, 1], array.ids)
172+
XCTAssertEqual(
173+
[
174+
ComparableValue(id: 2, value: 50),
175+
ComparableValue(id: 3, value: 75),
176+
ComparableValue(id: 1, value: 100),
177+
], array)
178+
}
179+
180+
func testSort() {
181+
var array: IdentifiedArray = [
182+
ComparableValue(id: 1, value: 100),
183+
ComparableValue(id: 2, value: 50),
184+
ComparableValue(id: 3, value: 75),
185+
]
186+
187+
array.sort()
188+
189+
XCTAssertEqual([2, 3, 1], array.ids)
190+
XCTAssertEqual(
191+
[
192+
ComparableValue(id: 2, value: 50),
193+
ComparableValue(id: 3, value: 75),
194+
ComparableValue(id: 1, value: 100),
195+
], array)
196+
197+
}
152198
}

0 commit comments

Comments
 (0)