Skip to content

[stdlib] Add Sequence.allSatisfy #15120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions stdlib/public/core/SequenceAlgorithms.swift
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,21 @@ extension Sequence {
}
return false
}

/// Returns a Boolean value indicating whether every element of a sequence
/// satisfies a given predicate.
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element satisfies a condition.
/// - Returns: `true` if the sequence contains only elements that satisfy
/// `predicate`; otherwise, `false`.
@inlinable
public func allSatisfy(
_ predicate: (Element) throws -> Bool
) rethrows -> Bool {
return try !contains { try !predicate($0) }
}
}

extension Sequence where Element : Equatable {
Expand Down
14 changes: 14 additions & 0 deletions validation-test/stdlib/SequenceType.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,20 @@ SequenceTypeTests.test("contains/Predicate") {
}
}

SequenceTypeTests.test("allSatisfy/Predicate") {
for test in findTests {
let s = MinimalSequence<OpaqueValue<Int>>(
elements: test.sequence.map { OpaqueValue($0.value) })
expectEqual(
test.expected == nil,
s.allSatisfy { $0.value != test.element.value },
stackTrace: SourceLocStack().with(test.loc))
expectEqual(
test.expectedLeftoverSequence.map { $0.value }, s.map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}

//===----------------------------------------------------------------------===//
// reduce()
//===----------------------------------------------------------------------===//
Expand Down