Skip to content

Commit 4315a00

Browse files
added contains(where:) function to VLArray
1 parent b505c7a commit 4315a00

File tree

2 files changed

+52
-3
lines changed

2 files changed

+52
-3
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
extension VLArray where Element: ~Copyable {
3+
/// Returns a Boolean value indicating whether the sequence contains an
4+
/// element that satisfies the given predicate.
5+
///
6+
/// - Parameter predicate: A closure that takes an element of the sequence
7+
/// as its argument and returns a Boolean value that indicates whether
8+
/// the passed element represents a match.
9+
/// - Returns: `true` if the sequence contains an element that satisfies
10+
/// `predicate`; otherwise, `false`.
11+
///
12+
/// - Complexity: O(*n*), where *n* is the length of the sequence.
13+
@inlinable
14+
public func contains(where predicate: (borrowing Element) throws -> Bool) rethrows -> Bool {
15+
for i in indices {
16+
if try predicate(self[i]) {
17+
return true
18+
}
19+
}
20+
return false
21+
}
22+
}

Tests/swift-variablelengtharrayTests/VariableLengthArrayTests.swift

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,16 +46,39 @@ struct VariableLengthArrayTests {
4646
}
4747

4848
@Test
49-
func clArrayNonCopyable() {
49+
func vlArrayNonCopyable() {
5050
let amount = 1
51-
VLArray<Noncopyable>.create(amount: amount, initialize: ({ .init(bro: $0) }), { array in
51+
VLArray<TestNonCopyable>.create(amount: amount, initialize: ({ .init(bro: $0) }), { array in
5252
#expect(array.count == amount)
5353
for i in array.indices {
5454
#expect(i == array[i].bro)
5555
}
5656
})
5757
}
5858

59+
@Test
60+
func vlArrayContains() {
61+
var amount = 3
62+
VLArray<TestCopyable>.create(amount: amount, initialize: ({ .init(bro: $0) })) { array in
63+
for i in 0..<amount {
64+
let contained = array.contains(where: { $0.bro == i })
65+
#expect(contained)
66+
}
67+
amount += 1
68+
let contained = array.contains(where: { $0.bro == amount })
69+
#expect(!contained)
70+
}
71+
VLArray<TestNonCopyable>.create(amount: amount, initialize: ({ .init(bro: $0) })) { array in
72+
for i in 0..<amount {
73+
let contained = array.contains(where: { $0.bro == i })
74+
#expect(contained)
75+
}
76+
amount += 1
77+
let contained = array.contains(where: { $0.bro == amount })
78+
#expect(!contained)
79+
}
80+
}
81+
5982
@Test
6083
func joinedVLArrayVL() {
6184
VLArray<UInt8>.create(amount: 5, default: 0) { first in
@@ -76,6 +99,10 @@ struct VariableLengthArrayTests {
7699
}
77100
}
78101

79-
struct Noncopyable: ~Copyable {
102+
struct TestCopyable {
103+
let bro:Int
104+
}
105+
106+
struct TestNonCopyable: ~Copyable {
80107
let bro:Int
81108
}

0 commit comments

Comments
 (0)