Swift Tutorial · Swift Basics · Lesson 6 of 30
Swift Strings
Work with strings and characters: common methods, multiline strings, Unicode-correct counting and substrings.
Common operations
Strings are value types and fully Unicode-aware: count counts characters as people see them, so an accented
letter counts as one even when it takes two bytes in UTF-8 or is written as a letter plus a combining accent.
import Foundation
let email = " [email protected] "
let clean = email.trimmingCharacters(in: .whitespaces).lowercased()
print(clean)
print(clean.count)
print(clean.hasSuffix(".com"), clean.contains("@"))
print(clean.replacingOccurrences(of: "example", with: "test"))
print("a,b,,c".split(separator: ",", omittingEmptySubsequences: false))
print("café".count, "café".utf8.count, "cafe\u{301}".count)
Output
[email protected] 21 true true [email protected] ["a", "b", "", "c"] 4 5 4
Run this on your computer — see “Get Started” for setup.
Multiline strings and substrings
Triple quotes create a multiline string; the closing quotes' indentation is removed from every line. Slicing a
string gives a Substring, which shares memory with the original; convert it with String(...) to keep it.
let name = "Ana"
let letter = """
Dear \(name),
Your order has shipped.
"""
print(letter)
let email = "[email protected]"
if let at = email.firstIndex(of: "@") {
let user = email[..<at] // Substring
let domain = String(email[email.index(after: at)...])
print(user, domain)
}
print(String(repeating: "ab", count: 3))
Output
Dear Ana, Your order has shipped. ana.silva example.com ababab
Run this on your computer — see “Get Started” for setup.
Test yourself
What does "café".count return?
4, because count counts user-visible characters53It doesn't compile
Show answer
Answer: 4, because count counts user-visible characters