Swift Strings
A string (String) is an ordered collection of characters, and is one of the most frequently used types in Swift.
Swift's strings are built on Unicode, so non-ASCII text such as Chinese and emoji can be handled naturally.
This article covers string creation, indexing, common methods, multiline syntax, Unicode views, and comparison; for the characters that make up a string, see 《Swift Characters》。
Creation, Concatenation, and Interpolation
A string can be created with a literal or initialized with String(); concatenation uses + or +=, and inserting variables into a string uses (...) interpolation.
Example
// Literals and initializers
let stringA
=
"Hello, World!"
let stringB
=
String
(
"Hello, World!"
)
(
stringA
)
(
stringB
)
// Concatenation
let constA
=
"Runoob Tutorial:"
let constB
=
"http://www.runoob.com"
(
constA
constB
)
var greet
=
"Runoob"
greet
=
" Tutorial"
(
greet
)
// Interpolation
let num
=
20
(
"(num) times 100 equals (num * 100)"
)
Running result:
Hello, World!
Hello, World!
Runoob Tutorial:http://www.runoob.com
Runoob 教程
20 乘于 100 等于 2000
An empty string can be created with "" or String(); to check whether it is empty, use isEmpty, which is more intuitive than comparing lengths.
Example
let emptyA
=
""
let emptyB
=
String
(
)
(
"emptyA is empty: (emptyA.isEmpty)"
)
(
"emptyB is empty: (emptyB.isEmpty)"
)
Running result:
emptyA 是空的:true
emptyB 是空的:true
The expression inside interpolation can be any valid Swift expression, and can also contain nested calls, but do not put complex logic into interpolation just to show off, as readability will suffer.
String.Index and Index Operations
Swift strings cannot use integer subscripts because different characters occupy different storage lengths, so String.Index is used for positioning.
The commonly used entry points are startIndex, endIndex, as well as index(_:offsetBy:), index(after:), and index(before:).
Example
let site
=
"www.runoob.com"
let start
=
site.
startIndex
// Count 3 forward from the beginning to get the index of the 4th character
let fourth
=
site.
index
(
start, offsetBy
:
3
)
(
"The 4th character: (site[fourth])"
)
// Use two indices to get a substring
let i4
=
site.
index
(
start, offsetBy
:
4
)
let i10
=
site.
index
(
start, offsetBy
:
10
)
(
"Substring from index 4 to 10: (site[i4 ..< i10])"
)
(
"Distance between the two indices: (site.distance(from: i4, to: i10))"
)
(
"At startIndex: (site[start])"
)
(
"One step forward: (site[site.index(after: start)])"
)
(
"Before endIndex: (site[site.index(before: site.endIndex)])"
)
Running result:
第 4 个字符:.
下标 4 到 10 的子串:runoob
两个下标的距离:6
startIndex 处:w
往后一格:w
endIndex 前一个:m
Note:endIndex refers to the last character'sfollowing position, which is not itself a valid character position, so you need to use index(before:) to get the last character.
An index can only come from the same string. Using an index computed from a different string to subscript may crash at runtime; this is the biggest difference between String.Index and integer subscripts.
// 2022-01-01 00:00:00 GMT
The table below lists the most commonly used members of strings; among them, prefix, suffix, and split return Substring or [Substring], which can be converted to String when needed.
| members | Description |
|---|---|
| count | Number of characters (extended grapheme clusters) |
| isEmpty | Whether it is an empty string |
| prefix(n) | Get the first n characters |
| suffix(n) | Get the last n characters |
| contains(_:) | Whether it contains a certain substring |
| hasPrefix(_:) | Whether it starts with a certain text |
| hasSuffix(_:) | Whether it ends with a certain text |
| split(separator:) | Split into an array of substrings by a separator |
| joined(separator:) | Join a sequence of strings into one string |
| replacingOccurrences(of:with:) | Replace a substring, requires import Foundation |
Example
import Foundation
let site
=
"www.runoob.com"
(
"Length: (site.count)"
)
(
"isEmpty:(site.isEmpty)"
)
(
"prefix(3):(site.prefix(3))"
)
(
"suffix(3):(site.suffix(3))"
)
(
"contains("runoob"):(site.contains("
runoob
"))"
)
(
"hasPrefix("www"):(site.hasPrefix("
www
"))"
)
(
"hasSuffix("com"):(site.hasSuffix("
com
"))"
)
// Splitting and joining
let csv
=
"Runoob,RUNOOB,Runoob Tutorial"
let parts
=
csv.
split
(
separator
:
","
)
(
"Number of split results: (parts.count)"
)
(
"First one: (parts[0])"
)
(
"joined restored: (parts.joined(separator: "
|
"))"
)
// Replace
let replaced
=
site.
replacingOccurrences
(
of
:
"runoob"
, with
:
"RUNOOB"
)
(
"After replacement: (replaced)"
)
Running result:
长度:14
isEmpty:false
prefix(3):www
suffix(3):com
contains("runoob"):true
hasPrefix("www"):true
hasSuffix("com"):true
split 结果个数:3
第一个:Runoob
joined 还原:Runoob | RUNOOB | Runoob Tutorial
替换后:www.RUNOOB.com
Note that hasPrefix(:) and hasSuffix(:) take a single unlabeled parameter; the hasPrefix(prefix:) form found in older tutorials has long been invalid.
split(separator:) discards empty substrings by default, so consecutive separators do not produce empty elements; to keep them, pass omittingEmptySubsequences: false.
Example
let site
=
"www.runoob.com"
let sub
=
site.
prefix
(
3
)
(
type
(
of
:
sub
)
)
let full
=
String
(
sub
)
(
type
(
of
:
full
)
)
Running result:
Substring
String
Multiline Strings and trimmingCharacters
Triple quotes can be used to write multiline strings; the common indentation matching the closing triple quotes is removed; if there is extra whitespace or newlines at the start or end of the string, use trimmingCharacters(in:) to clear them.
Example
import Foundation
let rawText
=
""
"
Runoob
www.runoob.com
"
""
(
"Original length: (rawText.count)"
)
let trimmed
=
rawText.
trimmingCharacters
(
in
:
.
whitespacesAndNewlines
)
(
"After trimming: |(trimmed)|"
)
Running result:
原始长度:22
裁剪后:|Runoob
www.runoob.com|
The indentation rule for multiline strings is: using the indentation of the line with the closing triple quotes as the baseline, that common indentation is removed from every line, so code layout and string content do not interfere with each other.
Other commonly used arguments for trimmingCharacters(in:) include .whitespaces (removes only spaces and tabs) and .newlines (removes only newlines).
Unicode Views
A single string can be viewed through three views of its underlying encoding: utf8 is a sequence of UTF-8 bytes, utf16 is a sequence of UTF-16 code units, and unicodeScalars is a sequence of Unicode scalars.
The element counts of the three views are often different, because one character may correspond to multiple scalars, and one scalar may correspond to multiple bytes.
Example
let unicodeString
=
"newbie"
(
"UTF-8:(Array(unicodeString.utf8))"
)
(
"UTF-16:(Array(unicodeString.utf16))"
)
(
"Unicode scalar values: (unicodeString.unicodeScalars.map { $0.value })"
)
Running result:
UTF-8:[232, 143, 156, 233, 184, 159]
UTF-16:[33756, 40479]
Unicode 标量值:[33756, 40479]
Note:UTF-8 is variable-length encoding; a Chinese character occupies 3 bytes, so a two-character Chinese string has 6 UTF-8 elements, while UTF-16 and Unicode scalars have only 2 each. Do not mistake utf8.count the element count for the character count.
To iterate over the characters users see, just use for c in str or Array(str); both go through the Character view; only when dealing with binary protocols or file formats do you need to drop down to utf8 or utf16.
String comparison
Swift uses == and != to check string equality, and uses << and > for lexicographic comparison.
Comparison is based on Unicode canonical equivalence: characters with different representations but identical appearance are treated as equal.
Example
let cmpA
=
"Hello, Swift!"
let cmpB
=
"Hello, World!"
(
"cmpA == cmpB:(cmpA == cmpB)"
)
(
"cmpA != cmpB:(cmpA != cmpB)"
)
(
"cmpA < cmpB:(cmpA < cmpB)"
)
Running result:
cmpA == cmpB:false
cmpA != cmpB:true
cmpA < cmpB:true
The following example illustrates "canonical equivalence": one uses a precomposed character, the other uses a letter plus a combining mark; their underlying code points are completely different, but the comparison result is equal.
Example
let cafe1
=
"caf\u{00E9}"
let cafe2
=
"cafe\u{0301}"
(
"The two forms are equal: (cafe1 == cafe2)"
)
(
"cafe1's count: (cafe1.count)"
)
(
"cafe2's count: (cafe2.count)"
)
Running result:
两种写法相等:true
cafe1 的 count:4
cafe2 的 count:4
Precisely because Swift's equality check follows canonical equivalence, using == to compare user input with preset text is reliable, and there is no need to do Unicode normalization yourself.
Common questions
The following questions come up most frequently when first learning Swift strings.
Why can't you use str[0] to get a character
Swift characters have variable length; one Character may occupy multiple bytes, and integer subscripts cannot locate them in constant time, so String.Index must be used.
Why are count and utf8.count different
count measures extended grapheme clusters, that is, the characters the eye sees; utf8.count measures bytes. A Chinese character is 1 in count and 3 in utf8.count.
What to do if hasPrefix(prefix:) reports an error
The modern form is hasPrefix(_:); just pass the prefix string to check directly, without a parameter label.
Why doesn't prefix return a String
It returns a Substring, which shares the underlying storage with the original string so the slice does not need to be copied; when you need an independent string, wrap it with String(...).
Is a string a value type or a reference type
It is a value type. Assignment and parameter passing semantically make a copy, but the compiler actually shares storage underneath and copies only on write, making it as safe to use as Int.