Skip to content

Commit 9f88e0e

Browse files
authored
Merge pull request #1 from SwiftMN/more-list-functions
add functions removeAll, contains, and first to ThreadSafeList
2 parents f36e0de + 766ecf9 commit 9f88e0e

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

Sources/ThreadSafeCollections/ThreadSafeList.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,12 @@ public class ThreadSafeList<V> {
6060
}
6161
}
6262

63+
public func removeAll(where shouldBeRemoved: @escaping (V) -> Bool) {
64+
itemQueue.async(flags: .barrier) { // safely write
65+
self.items.removeAll(where: shouldBeRemoved)
66+
}
67+
}
68+
6369
public func getAll() -> [V] {
6470
var allItems = [V]()
6571
itemQueue.sync { // safely read
@@ -76,6 +82,22 @@ public class ThreadSafeList<V> {
7682
return count
7783
}
7884

85+
public func contains(where predicate: (V) throws -> Bool) rethrows -> Bool {
86+
var doesContain = false
87+
try itemQueue.sync { // safely read
88+
doesContain = try self.items.contains(where: predicate)
89+
}
90+
return doesContain
91+
}
92+
93+
public func first(where predicate: (V) throws -> Bool) rethrows -> V? {
94+
var foundItem: V? = nil
95+
try itemQueue.sync { // safely read
96+
foundItem = try self.items.first(where: predicate)
97+
}
98+
return foundItem
99+
}
100+
79101
public subscript(index: Int) -> V? {
80102
get {
81103
return self.get(index)

Tests/ThreadSafeCollectionsTests/ThreadSafeCollectionsTests.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ final class ThreadSafeCollectionsTests: XCTestCase {
3838
XCTAssertEqual(0, m.count())
3939
m.append(contentsOf: items)
4040
XCTAssertEqual(100, m.count())
41+
XCTAssertTrue(m.contains(where: { $0 == 5 }))
42+
XCTAssertEqual(5, m.first(where: { $0 == 5 }))
43+
m.removeAll(where: { $0 == 5 })
44+
XCTAssertFalse(m.contains(where: { $0 == 5 }))
45+
XCTAssertNil(m.first(where: { $0 == 5 }))
4146
}
4247

4348
}

0 commit comments

Comments
 (0)