Strings and Characters
In this page:
Declaring Strings and Characters
A String holds a sequence of text, while a Character holds exactly one visible character, often used when processing text one symbol at a time.
Example: Declaring Strings and Characters
let greeting: String = "Hello"
let firstLetter: Character = "H"
print("\(greeting) starts with \(firstLetter)")
Login to try C/C++/Java/PHP code in the editor
Concatenation and Interpolation
Strings can be joined together with the + operator, or embedded into other strings using interpolation with \(expression).
Example: Concatenation and Interpolation
let first = "Swift"
let second = "Lang"
let combined = first + " " + second
print(combined)
print("Combined has \(combined.count) characters")
Login to try C/C++/Java/PHP code in the editor
Common String Properties and Methods
Strings expose useful properties like .count, .isEmpty, .uppercased(), and .lowercased() for common text operations.
Example: Common String Properties and Methods
let message = "Hello, Swift!"
print("Uppercase: \(message.uppercased())")
print("Length: \(message.count)")
print("Is empty: \(message.isEmpty)")
Login to try C/C++/Java/PHP code in the editor
Iterating Over Characters
Since strings can't be indexed by integer, the idiomatic way to visit each character is to iterate over the string directly in a for-in loop.
Note: This correctly handles Unicode characters that might be built from multiple underlying scalars.
Example: Iterating Over Characters
let word = "Swift"
for letter in word {
print(letter)
}
Login to try C/C++/Java/PHP code in the editor
- Trying to index a
Stringwith an integer likestr[0]; Swift strings useString.Indexbecause of Unicode, not plain integer offsets. - Using
+to build a large string in a loop repeatedly, which is less efficient than appending with+=or building an array and joining. - Forgetting that a
Charactercan represent a multi-scalar grapheme cluster (like an emoji with a modifier), not just a single simple letter.
Stringrepresents text, andCharacterrepresents a single grapheme cluster (visible character).- Strings can't be indexed with plain integers; use
.first,.last, orString.Indexnavigation instead. - String interpolation (
\(value)) and concatenation (+) both build new strings. - Swift strings are fully Unicode-correct, which is why simple integer indexing isn't allowed.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: