Chapter 30: Strings
1. What is a String in Swift? (the most important big picture)
A String is an ordered collection of characters — basically, text.
But Swift strings are smarter and safer than in many other languages:
- They support full Unicode (emoji, Hindi, Telugu, Arabic, Chinese, Japanese, flags, skin tones…)
- They count human-visible characters (not bytes or code points)
- Strings are value types → when you assign or pass them, a copy is made
- Strings are immutable when declared with let → you cannot change their content
- Strings are mutable when declared with var → you can append, replace, remove…
|
0 1 2 3 4 5 6 7 |
let fixedMessage = "Namaste, Hyderabad! 🌶️" // cannot be changed var changeable = "Hello" // can be changed later |
2. Creating Strings – all the common ways you’ll actually use
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// 1. Simple string literal (most common) let name = "Sneha" // 2. Empty string (very frequent) let empty1 = "" let empty2 = String() // same thing // 3. Multi-line string (super clean – used all the time) let aboutMe = """ Hi, I'm learning Swift. I live in Hyderabad. My favorite emoji is 😊🚀 """ // 4. String interpolation – #1 way to combine text + values let age = 19 let city = "Hyderabad" let intro = "My name is \(name), I am \(age) years old, from \(city)." // 5. Raw string – ignores escape characters (very useful) let regexPattern = #"\d{3}-\d{3}-\d{4}"# let filePath = #"C:\Users\Public\Documents\report.pdf"# let jsonExample = #"{ "name": "Priya", "age": 24 }"# |
Quick tip: Use raw strings (#”…# ) whenever you have backslashes (\) or quotes (“) — it saves you from writing lots of \\ and \”.
3. Most Important String Properties & Methods (you will use these 100 times)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
let message = "Swift is modern, safe, and fun! 😊🚀" // Length (counts characters, not bytes) print(message.count) // 35 // Empty check (very common) print(message.isEmpty) // false print("".isEmpty) // true // Case conversion print(message.uppercased()) // SWIFT IS MODERN, SAFE, AND FUN! 😊🚀 print(message.lowercased()) // swift is modern, safe, and fun! 😊🚀 // Prefix / suffix check print(message.hasPrefix("Swift")) // true print(message.hasSuffix("🚀")) // true // Contains print(message.contains("modern")) // true print(message.contains("old")) // false // Replace (returns new string – original unchanged) let updated = message.replacingOccurrences(of: "fun", with: "powerful") print(updated) // Swift is modern, safe, and powerful! 😊🚀 // Trim whitespace (very common for user input) let dirtyInput = " hello " let clean = dirtyInput.trimmingCharacters(in: .whitespacesAndNewlines) print("[\(clean)]") // [hello] |
4. Looping over characters – very common & very useful
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let word = "नमस्ते 😊" for char in word { print(char) } // Output: // न // म // स // ् // त // े // (space) // 😊 |
Important things to understand:
- You loop over grapheme clusters (what humans see as one character)
- “😊”.count == 1
- “नमस्ते”.count == 6 (even though it looks like 6 characters)
This is different from many older languages that count bytes or Unicode scalars.
5. String Interpolation – the modern, clean way to build text
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let product = "iPhone 16 Pro" let price = 119900 let rating = 4.85 let description = """ Product: \(product) Price: ₹\(price) Rating: \(rating) / 5 """ print(description) |
Advanced interpolation (very popular 2024–2026 style)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let temp = 36.7 let health = """ Temperature: \(temp, format: .number.precision(.fractionLength(1)))°C Status: \(temp > 38 ? "Fever 😷" : "Normal 🌡️") """ print(health) |
6. Working with parts of a string (substrings, prefix, suffix)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
let fullName = "Sneha Reddy" // First character if let first = fullName.first { print("First letter: \(first)") // S } // Last character if let last = fullName.last { print("Last letter: \(last)") // y } // First 5 characters let firstFive = fullName.prefix(5) // "Sneha" // Everything after first space if let spaceIndex = fullName.firstIndex(of: " ") { let lastName = fullName[fullName.index(after: spaceIndex)...] print("Last name: \(lastName)") // Reddy } |
Modern & safe way (avoid force-unwrap)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let email = "aarav@example.com" if let atIndex = email.firstIndex(of: "@") { let username = email[..<atIndex] // "aarav" let domain = email[email.index(after: atIndex)...] // "example.com" } |
7. Very Common Real-Life Examples (you will write these)
Example 1 – Clean username validation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
func isValidUsername(_ input: String) -> Bool { let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines) return !trimmed.isEmpty && trimmed.count >= 3 && trimmed.count <= 20 && trimmed.allSatisfy { char in char.isLetter || char.isNumber || char == "_" || char == "." } } print(isValidUsername("aarav_007")) // true print(isValidUsername(" a ")) // false |
Example 2 – Simple phone number formatting
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
func formatIndianPhone(_ number: String) -> String { let digitsOnly = number.filter { $0.isNumber } guard digitsOnly.count == 10 else { return number } let prefix = "+91 " let part1 = digitsOnly.prefix(5) let part2 = digitsOnly.dropFirst(5) return prefix + part1 + " " + part2 } print(formatIndianPhone("9876543210")) // +91 98765 43210 print(formatIndianPhone("987 654 3210")) // same |
Example 3 – Password strength indicator
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
func passwordStrength(_ password: String) -> String { guard !password.isEmpty else { return "Too short" } let lengthScore = password.count >= 12 ? 3 : password.count >= 8 ? 2 : 1 let hasUpper = !password.lowercased().elementsEqual(password) let hasLower = !password.uppercased().elementsEqual(password) let hasDigit = password.rangeOfCharacter(from: .decimalDigits) != nil let hasSymbol = password.range(of: "[!@#$%^&*()_+=]", options: .regularExpression) != nil let variety = [hasUpper, hasLower, hasDigit, hasSymbol].filter { $0 }.count let totalScore = lengthScore + variety switch totalScore { case 6...7: return "Very Strong 💪" case 4...5: return "Strong 👍" case 2...3: return "Medium 😐" default: return "Weak 😟" } } print(passwordStrength("Passw0rd!")) // Strong 👍 print(passwordStrength("abc123")) // Medium 😐 |
8. Quick Summary – Most Important String Operations
| Goal | Best modern code example | Notes / Tip |
|---|---|---|
| Build text with variables | “Hi \(name), age: \(age)” | Interpolation – #1 method |
| Multi-line text | “”” … “”” | Cleanest way |
| Length | text.count | Counts visible characters (emoji = 1) |
| Empty check | text.isEmpty | Fast & clear |
| Upper / lower | text.uppercased(), text.lowercased() | Use for case-insensitive comparison |
| Contains substring | text.contains(“word”) | Simple & fast |
| Replace text | text.replacingOccurrences(of: “old”, with: “new”) | Returns new string |
| Trim whitespace | text.trimmingCharacters(in: .whitespacesAndNewlines) | Clean user input |
| Loop over each character | for char in text { … } | Each char is a Character |
9. Small Practice – Try these now
- Create a welcome message with name, age, city using interpolation
- Write a function that checks if a string contains both “@” and “.” (basic email check)
- Format a 10-digit Indian phone number like: +91 XXXXX XXXXX
Paste your code if you want feedback!
What would you like to explore more deeply next?
- Advanced string manipulation (regular expressions, splitting, joining, prefix/suffix)
- Strings + optionals (very common in real apps)
- Strings in SwiftUI (Text, formatting, markdown)
- Performance & mutability (String vs NSMutableString vs Substring)
- Unicode, emoji, flags, skin tones in detail
- Or move to another topic (arrays, dictionaries, optionals, structs…)
Just tell me — we’ll continue in the same detailed, patient, teacher-like style 😊
