Chapter 29: Swift Strings

1. What is a String in Swift?

A String is a sequence of characters — basically, text.

In Swift:

  • A String can contain letters, numbers, symbols, emoji, Unicode characters from any language (Hindi, Telugu, Arabic, Chinese, Japanese, etc.)
  • Strings are value types → when you assign or pass them, a copy is made
  • Strings are immutable when declared with let (you cannot change the content)
  • Strings are mutable when declared with var (you can change, append, replace)
Swift

2. Creating Strings – all the common ways

Swift

3. Most Useful String Properties & Methods (you use these every day)

Swift

4. Looping over characters (very common pattern)

Swift

Important: Swift loops over grapheme clusters (human-visible characters), not Unicode scalars or bytes.

That’s why “😊”.count == 1 and “नमस्ते”.count == 6 (even though it looks like 6 characters).

5. String Interpolation – the modern way to build text

Swift

Advanced interpolation (very clean 2024–2026 style)

Swift

6. Working with substrings & indices (important but tricky)

Swift

Modern & safer way (most common 2025 style)

Swift

7. Very Common Real-Life Examples

Example 1 – Username validation

Swift

Example 2 – Phone number formatting (very common)

Swift

Example 3 – Password strength meter

Swift

8. Quick Summary – Most Used String Operations

Goal Best code example Notes
Build message with values “Hi \(name), age: \(age)” String interpolation – #1 method
Multi-line text “”” … “”” Clean & readable
Length text.count Counts characters (emoji = 1)
Check empty text.isEmpty or text == “”
Upper / lower text.uppercased(), text.lowercased() For case-insensitive comparison
Contains text.contains(“word”) Simple substring check
Replace text.replacingOccurrences(of: “old”, with: “new”) Immutable – returns new string
Trim whitespace text.trimmingCharacters(in: .whitespacesAndNewlines) Removes leading/trailing spaces
Loop over characters for char in text { … } Each char is a Character

9. Small Practice – Try these

  1. Create a greeting message with name, age, city using interpolation
  2. Check if a string contains both “@” and “.” (simple email check)
  3. Format a 10-digit phone number as +91 XXXXX XXXXX

Paste your attempts if you want feedback!

What would you like to explore more deeply next?

  • Advanced string manipulation (regular expressions, splitting, joining)
  • String performance & mutability (String vs NSMutableString)
  • Unicode & emoji handling in detail
  • Strings in SwiftUI (Text, labels, formatting)
  • Or move to another topic (arrays, dictionaries, optionals, functions…)

Just tell me — we’ll continue in the same clear, detailed, teacher-like way 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *