split(maxSplits:omittingEmptySubsequences:whereSeparator:)

Lazily returns the longest possible subsequences of the collection, in order, that don’t contain elements satisfying the given predicate.

Split.swift:645
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: @escaping (Element) -> Bool) -> SplitCollection<Elements>

Parameters

maxSplits

The maximum number of times to split the collection, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original collection containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max.

omittingEmptySubsequences

If false, an empty subsequence is returned in the result for each pair of consecutive elements satisfying the isSeparator predicate and for each element at the start or end of the collection satisfying the isSeparator predicate. The default value is true.

whereSeparator

A closure that takes an element as an argument and returns a Boolean value indicating whether the collection should be split at that element.

Returns

A lazy collection of subsequences, split from this collection’s elements.

The resulting lazy collection consists of at most maxSplits + 1 subsequences. Elements that are used to split the collection are not returned as part of any subsequence (except possibly the last one, in the case where maxSplits is less than the number of separators in the collection).

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when lazily splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
for spaceless in line.lazy.split(whereSeparator: { $0 == " " }) {
  print(spaceless)
}
// Prints
// BLANCHE:
// I
// don't
// want
// realism.
// I
// want
// magic!

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

for spaceless in line.lazy.split(
  maxSplits: 1,
  whereSeparator: { $0 == " " }
) {
  print(spaceless)
}
// Prints
// BLANCHE:
// I don't want realism. I want magic!

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

for spaceless in line.lazy.split(
  omittingEmptySubsequences: false,
  whereSeparator: { $0 == " " }
) {
  print(spaceless)
}
// Prints
// BLANCHE:
//
//
// I
// don't
// want
// realism.
// I
// want
// magic!