partitioned(by:)
Returns two arrays containing, in order, the elements of the sequence that do and don’t satisfy the given predicate.
func partitioned(by predicate: (Element) throws -> Bool) rethrows -> (falseElements: [Element], trueElements: [Element])
Parameters
- predicate
A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the second returned array. Otherwise, the element will appear in the first returned array.
Returns
Two arrays with all of the elements of the receiver. The first array contains all the elements that predicate
didn’t allow, and the second array contains all the elements that predicate
allowed.
In this example, partitioned(by:)
is used to separate the input based on whether a name is shorter than five characters:
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
print(longNames)
// Prints "["Vivien", "Marlon"]"
print(shortNames)
// Prints "["Kim", "Karl"]"