← Back to Swift Course | Chapter 2: Variables & Types | Lesson 7 of 8

Strings and Characters

A string is a piece of text, like a word or sentence, and a character is just one single letter or symbol from that text.

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

markup
let greeting: String = "Hello"
let firstLetter: Character = "H"
print("\(greeting) starts with \(firstLetter)")

Concatenation and Interpolation

Strings can be joined together with the + operator, or embedded into other strings using interpolation with \(expression).

Example: Concatenation and Interpolation

markup
let first = "Swift"
let second = "Lang"
let combined = first + " " + second
print(combined)
print("Combined has \(combined.count) characters")

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

markup
let message = "Hello, Swift!"
print("Uppercase: \(message.uppercased())")
print("Length: \(message.count)")
print("Is empty: \(message.isEmpty)")

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

markup
let word = "Swift"
for letter in word {
    print(letter)
}
Common Mistakes
  1. Trying to index a String with an integer like str[0]; Swift strings use String.Index because of Unicode, not plain integer offsets.
  2. Using + to build a large string in a loop repeatedly, which is less efficient than appending with += or building an array and joining.
  3. Forgetting that a Character can represent a multi-scalar grapheme cluster (like an emoji with a modifier), not just a single simple letter.
Chapter Summary
  • String represents text, and Character represents a single grapheme cluster (visible character).
  • Strings can't be indexed with plain integers; use .first, .last, or String.Index navigation 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.