Swift example

How to split a string in Swift

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Call split(separator:): "a,b,c".split(separator: ",") gives ["a", "b", "c"]. The pieces are Substring values, so add .map(String.init) when you need [String]. Empty pieces are dropped unless you pass omittingEmptySubsequences: false. To turn a string into an array of its characters, write Array(text).

Swift has two families of split functions. The standard library's split needs no import, returns Substring pieces that share the original string's memory, and drops empty pieces by default. Foundation's components(separatedBy:) returns [String] and keeps every empty field. The sections below cover both, splitting on whitespace and on lines (where "\r\n" catches people out), splitting with a regex, and turning a string into an array of characters, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1split(separator:)Recommended

split(separator:) is a standard library method, so it works without import Foundation. It returns [Substring]: each piece is a view into the original string rather than a copy, which makes splitting cheap. Most APIs want a String, so convert with map(String.init) when you store or return the pieces. Two arguments change the result: omittingEmptySubsequences: false keeps empty fields, and maxSplits stops after that many splits and leaves the rest in the last piece. The separator can be a single character or a longer string.

split.swift
let csv = "red,green,,blue"

// split returns [Substring]; empty pieces are dropped by default
let parts = csv.split(separator: ",")
print(parts)

// Convert to [String] when you store or return the pieces
let colors: [String] = parts.map(String.init)
print(colors.count, colors)

// Keep the empty field between the two commas
print(csv.split(separator: ",", omittingEmptySubsequences: false))

// maxSplits: 1 splits at the first separator only
print("token=YWJj==".split(separator: "=", maxSplits: 1))

// A separator longer than one character
print("a, b, c".split(separator: ", "))

// Numbers: convert each piece, skipping any that don't parse
print("2026-12-01".split(separator: "-").compactMap { Int($0) })

// Check the count before you index into the result
let pair = "name:Ada".split(separator: ":")
if pair.count == 2 {
    print("key \(pair[0]), value \(pair[1])")
}

Output

The default split of "red,green,,blue" returns three pieces: the empty field between the two commas is gone. With omittingEmptySubsequences: false it comes back as "", which is what you want for CSV-like data where a column position matters. maxSplits: 1 keeps the == padding in "YWJj==" instead of cutting it off. Int($0) takes a Substring directly, so the date becomes [2026, 12, 1] with no conversion step. Assigning a piece to a String variable without converting fails to compile with cannot convert value of type 'String.SubSequence' (aka 'Substring') to specified type 'String', and reading parts[3] when there are only three pieces crashes with Fatal error: Index out of range, hence the count check.

2components(separatedBy:) from Foundation

components(separatedBy:) comes from Foundation and is the answer in many older Stack Overflow posts (in Swift 2 it was spelled componentsSeparatedByString). It returns [String], so there is nothing to convert, and it always keeps empty fields. The separator is a String of any length, or a CharacterSet to split on any one of several characters. It needs import Foundation.

components.swift
import Foundation

let csv = "red,green,,blue"

// components(separatedBy:) returns [String] and keeps empty fields
let fields = csv.components(separatedBy: ",")
print(fields)

// The separator is a String of any length
print("one :: two :: three".components(separatedBy: " :: "))

// A CharacterSet splits on any one of several characters
let mixed = "one;two|three"
print(mixed.components(separatedBy: CharacterSet(charactersIn: ";|")))
print("a1b22c".components(separatedBy: .decimalDigits))

// The empty string: one empty field here, no pieces from split
print("".components(separatedBy: ","))
print("".split(separator: ","))

Output

The same CSV line gives four fields here, the empty one included. With a CharacterSet, every matching character is its own separator, so the two digits in "22" leave an empty string between them: ["a", "b", "", "c"]. The last two lines show a real difference for empty input: components returns [""], one empty field, while split returns []. Code that reads fields[0] works on the first and crashes on the second.

3Splitting on whitespace and into lines

To split text into words, split(separator: " ") is close but not right: it ignores tabs and newlines. split(whereSeparator:) takes a test instead of a fixed separator, and the key paths \.isWhitespace and \.isNewline are the tests you want. Because empty pieces are dropped, a run of spaces counts as one break. Splitting into lines has its own trap: Swift treats "\r\n", the Windows line ending, as a single Character, so it is not equal to "\n".

words_lines.swift
import Foundation

let text = "  hello   big\tworld\n"

// A single space as the separator misses tabs and newlines
print(text.split(separator: " "))

// Split on any whitespace; a run of it counts as one break
print(text.split(whereSeparator: \.isWhitespace))

// The Foundation version leaves empty strings to filter out
let raw = text.components(separatedBy: .whitespacesAndNewlines)
print(raw.count, raw.filter { !$0.isEmpty })

// Lines: isNewline matches \n, \r\n and the other line breaks
let file = "first\nsecond\r\nthird\n\nfifth\n"
print(file.split(whereSeparator: \.isNewline))

// Gotcha: "\r\n" is one Character, so splitting on "\n" misses it
print(file.split(separator: "\n"))

// Keep blank lines with omittingEmptySubsequences: false
let withBlanks = file.split(
    omittingEmptySubsequences: false, whereSeparator: \.isNewline
)
print(withBlanks)

Output

Splitting on " " leaves "big\tworld\n" as one piece. \.isWhitespace gives the three words, and so does components(separatedBy: .whitespacesAndNewlines), but only after a filter: it produced 8 pieces, five of them empty. For lines, \.isNewline splits at the \r\n too, while split(separator: "\n") returns "second\r\nthird" as one line. That is the bug to expect when a file comes from Windows. The last call keeps the blank line and also the empty string after the final newline, so drop the last element if the text ends with one.

4Splitting with a regex

When the separator varies, such as a comma or a semicolon with optional spaces around it, pass a regex to the same split(separator:). Swift 5.7 added Regex and regex literals, so no import is needed. The literal on this page is written #/…/#; the bare /…/ form works in the Swift 6 language mode and in Xcode projects with bare-slash regex literals enabled, but not in the default mode used here. For a pattern built at run time, use try Regex("…"), which throws on an invalid pattern. Older answers use NSRegularExpression to do the same in many more lines.

regex_split.swift
let messy = "one, two;three  ,four"

// A regex separator: a comma or semicolon with any spaces around it
print(messy.split(separator: #/\s*[,;]\s*/#))

// Runs of digits, or of whitespace, as the separator
print("a1b22c333d".split(separator: #/\d+/#))
print("too   many    spaces".split(separator: #/\s+/#))

// maxSplits and omittingEmptySubsequences work the same way
print("a--b----c".split(separator: #/-+/#, maxSplits: 1))

// A pattern built at run time: Regex(_:) throws if it is invalid
let delimiters = ",;"
let pattern = try Regex("[\(delimiters)]")
print("x,y;z".split(separator: pattern))

do {
    _ = try Regex("[a-")
} catch {
    print("invalid pattern:", error)
}

Output

The pattern \s*[,;]\s* eats the spaces with the separator, so "one, two;three ,four" comes out as four clean words with no trimming step. \d+ treats "22" and "333" as one separator each, unlike the CharacterSet in section 2. With maxSplits: 1 the rest, "b----c", stays whole. The bad pattern "[a-" is caught at run time with the message expected ']'; a bad #/…/# literal is a compile error instead.

5A string to an array of characters

A String is already a collection of Character values, so Array(text) turns it into [Character] with no separator at all. If you need one-letter strings, use map(String.init). A Swift Character is what a reader sees as one character, so an accented letter or an emoji with a skin tone stays in one piece even when it is made of several Unicode scalars. Old answers call text.characters; that no longer compiles: 'characters' is unavailable: Please use String directly.

characters.swift
let word = "Swift"

// Array(string) gives one Character per element
let chars = Array(word)
print(chars)

// map(String.init) when you want one-letter Strings instead
let letters = word.map(String.init)
print(letters)

// Characters are what you see: an accent or a skin tone stays whole
let text = "café 👍🏽!"
print(Array(text), text.count)

// Lower levels: Unicode scalars and UTF-8 bytes
print(text.unicodeScalars.map(\.value))
print(Array(text.utf8).count, "bytes")

// Digits to numbers
print("2048".compactMap(\.wholeNumberValue))

// And back: String(_:) joins Characters, joined() joins Strings
print(String(chars.reversed()))
print(letters.joined(separator: "-"))

Output

The first two lines print the same, but the types differ: [Character] and [String]. "café 👍🏽!" splits into 7 characters, with "👍🏽" as one element, while its Unicode scalars number 8 (the thumb and the skin tone, 128077 and 127997, are separate) and its UTF-8 encoding takes 15 bytes. Pick the level your task needs: characters for anything a person reads, bytes for encoding work. wholeNumberValue turns digit characters into [2, 0, 4, 8], and String(chars.reversed()) builds a string back from characters. More on counting in getting the length of a string.

6Which should you use?

MethodReturnsBest for
s.split(separator: ",")[Substring], empties droppedMost splitting; no import needed
s.split(separator: ",", omittingEmptySubsequences: false)[Substring], empties keptFields where position matters, like CSV columns
s.components(separatedBy: ",")[String], empties keptCode that already uses Foundation; CharacterSet separators
s.split(whereSeparator: \.isWhitespace)[Substring], no emptiesWords separated by any spaces, tabs or newlines
s.split(whereSeparator: \.isNewline)[Substring], one per lineLines, including Windows \r\n endings
s.split(separator: #/\s*[,;]\s*/#)[Substring]Separators that vary: several characters, optional spaces
Array(s)[Character]One element per character, no separator

Frequently asked questions

How do I convert [Substring] to [String] in Swift?

Map each piece through the String initializer: let words = text.split(separator: " ").map(String.init). For a single piece, write String(parts[0]). Many functions accept a Substring as it is (Int(piece) does), so convert only when a type asks for String or you keep the pieces around.

Why does split return Substring instead of String?

A Substring shares memory with the string it came from, so splitting a large text does not copy every piece. The flip side is that a stored Substring keeps the whole original string in memory. Use the pieces right away, or convert the ones you keep to String.

What is the difference between split and components(separatedBy:)?

split(separator:) is in the standard library, returns [Substring], drops empty pieces unless you pass omittingEmptySubsequences: false, and takes maxSplits. components(separatedBy:) needs import Foundation, returns [String], always keeps empty fields, and accepts a CharacterSet. On an empty string, split gives [] and components gives [""].

How do I split a string into an array of characters?

Use Array(text) for [Character], or text.map(String.init) for [String]. Each element is one character as a reader sees it, so "café 👍🏽!" gives 7 elements. For the numeric code points use text.unicodeScalars, and for bytes use Array(text.utf8).

How do I split a string into lines in Swift?

Use text.split(whereSeparator: \.isNewline). It splits at \n, at Windows \r\n and at the other line breaks, and drops blank lines. split(separator: "\n") misses \r\n, because Swift treats \r\n as one Character. Pass omittingEmptySubsequences: false to keep blank lines.

How do I get the first part of a split, or split only once?

Pass maxSplits: 1: "token=YWJj==".split(separator: "=", maxSplits: 1) gives ["token", "YWJj=="]. Read the result with parts.first, which is optional, or check parts.count before indexing: reading past the end crashes with Fatal error: Index out of range.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground