Instance Method


Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.


func split(separator: UInt8, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [Data]



The element that should be split upon.


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.


If false, an empty subsequence is returned in the result for each consecutive pair of separator elements in the collection and for each instance of separator at the start or end of the collection. If true, only nonempty subsequences are returned. The default value is true.

Return Value

An array of subsequences, split from this collection’s elements.


The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the collection are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string at each space character (” “). 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!"
print(line.split(separator: " "))
// 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.

print(line.split(separator: " ", maxSplits: 1))
// 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.

print(line.split(separator: " ", omittingEmptySubsequences: false))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Complexity: O(n), where n is the length of the collection.

See Also

Splitting the Buffer

func subdata(in: Range<Data.Index>) -> Data

Returns a new copy of the data in a specified range.

func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (UInt8) -> Bool) -> [Data]

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

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software