Swift String split()

The split() method breaks up a string at the specified separator and returns an array of strings.

Example

var text = "Swift is a fun programming language"

// split the text from space print(text.split(separator: " "))
// Output: ["Swift", "is", "a", "fun", "programming", "language"]

split() Syntax

The syntax of split() is:

string.split(separator: Character, maxSplits: Int, ommittingEmptySequence: Bool)

Here, string is an object of the String class.


split() Parameters

The split() method can take three parameters:

  • separator - Delimiter at which splits occur.
  • maxSplits (optional) - Maximum number of splits. If not provided, there is no limit on the number of splits.
  • omittingEmptySubsequences (optional) - specifies whether to omit empty string elements or to include them

Note: If maxSplits is specified, the array will have a maximum of maxSplits + 1 items.


split() Return Value

  • returns an array of substrings

Example 1: Swift split()

var text = "Swift is awesome. Swift is fun."

// split at period "." print(text.split(separator: "."))
// split string with limit print(text.split(separator: " ", maxSplits: 2))

Output

["Swift is awesome", " Swift is fun"]
["Swift", "is", "awesome. Swift is fun."]

Example 2: split() with omittingEmptySubsequences Parameter

var text = "Swift  is a fun programming language"

// split the text from space
// returned array doesn't contain empty string print(text.split(separator: " ", maxSplits: 2, omittingEmptySubsequences: true))
// returned array contains empty string print(text.split(separator: " ", maxSplits: 2, omittingEmptySubsequences: false))

Output

["Swift", "is", "a fun programming language"]
["Swift", "", "is a fun programming language"]
Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community