Working with Strings
Prerequisites: Strings
Strings come with many built-in properties and methods. A few more
come from Foundation, Apple's standard library of utilities —
add import Foundation at the top of the file to use them (it's
available on every platform Swift runs on).
Example
import Foundation
let text = " Hello, Swift World "
let trimmed = text.trimmingCharacters(in: .whitespaces)
print(trimmed)
print(trimmed.uppercased())
print(trimmed.lowercased())
print(trimmed.count)
print(trimmed.hasPrefix("Hello"))
print(trimmed.hasSuffix("!"))
print(trimmed.contains("Swift"))
print(trimmed.replacingOccurrences(of: "World", with: "Friends"))
print("a,b,c".split(separator: ","))
print(String("Swift".reversed()))
print("".isEmpty)
Expected output
Hello, Swift World
HELLO, SWIFT WORLD
hello, swift world
18
true
false
true
Hello, Swift Friends
["a", "b", "c"]
tfiwS
true
Methods like uppercased() return a new string — the original is
unchanged. Strings in Swift are values, not shared objects.
Characters and Unicode
Swift strings handle every language and emoji correctly. count
counts characters as a person would see them:
print("café".count)
print("👍🏽".count)
for letter in "Hi!" {
print(letter)
}
4
1
H
i
!
That thumbs-up with a skin tone is several Unicode code points, but one character — which is what Swift counts.
Getting characters by position
Because characters can take different amounts of memory, Swift
strings can't be indexed with a plain number like text[0].
Use first, last, prefix, and dropFirst, or convert to an array:
let word = "Swift"
print(word.first!)
print(word.prefix(3))
print(word.dropFirst(2))
print(Array(word)[1])
S
Swi
ift
w
(The ! after first is explained in the Optionals lessons — first
could be missing if the string were empty.)
Common mistakes
- Writing
text[0]—'subscript(_:)' is unavailable: cannot subscript String with an Int. Usefirst,prefix, orArray(text). - Forgetting
import Foundationfor methods liketrimmingCharacters(in:)andreplacingOccurrences(of:with:).
Practice
Given let email = " Ada@Example.COM ", print it trimmed and in
lowercase.
Show solution
import Foundation
let email = " Ada@Example.COM "
print(email.trimmingCharacters(in: .whitespaces).lowercased())
ada@example.com