Skip to content

Commit

Permalink
Merge pull request #1 from SwiftMN/more-list-functions
Browse files Browse the repository at this point in the history
add functions removeAll, contains, and first to ThreadSafeList
  • Loading branch information
vlaminck authored Mar 24, 2020
2 parents f36e0de + 766ecf9 commit 9f88e0e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Sources/ThreadSafeCollections/ThreadSafeList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ public class ThreadSafeList<V> {
}
}

public func removeAll(where shouldBeRemoved: @escaping (V) -> Bool) {
itemQueue.async(flags: .barrier) { // safely write
self.items.removeAll(where: shouldBeRemoved)
}
}

public func getAll() -> [V] {
var allItems = [V]()
itemQueue.sync { // safely read
Expand All @@ -76,6 +82,22 @@ public class ThreadSafeList<V> {
return count
}

public func contains(where predicate: (V) throws -> Bool) rethrows -> Bool {
var doesContain = false
try itemQueue.sync { // safely read
doesContain = try self.items.contains(where: predicate)
}
return doesContain
}

public func first(where predicate: (V) throws -> Bool) rethrows -> V? {
var foundItem: V? = nil
try itemQueue.sync { // safely read
foundItem = try self.items.first(where: predicate)
}
return foundItem
}

public subscript(index: Int) -> V? {
get {
return self.get(index)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ final class ThreadSafeCollectionsTests: XCTestCase {
XCTAssertEqual(0, m.count())
m.append(contentsOf: items)
XCTAssertEqual(100, m.count())
XCTAssertTrue(m.contains(where: { $0 == 5 }))
XCTAssertEqual(5, m.first(where: { $0 == 5 }))
m.removeAll(where: { $0 == 5 })
XCTAssertFalse(m.contains(where: { $0 == 5 }))
XCTAssertNil(m.first(where: { $0 == 5 }))
}

}

0 comments on commit 9f88e0e

Please sign in to comment.