Working with Strings
1. Creating Strings
| Method | Description | Example |
|---|---|---|
| String.init() | Creates an empty string | let emptyString = String() |
| String(repeating:count:) | Creates a string by repeating a character or string | let repeatedString = String(repeating: "๐", count: 3) |
| String(format:arguments:) | Creates a string using format specifiers (like C's printf) | let formatted = String(format: "Hello %s, you are %d years old", "Alice", 25) |
| String(Character) | Creates a string from a single character | let charString = String("A") |
| String(CharacterCollection) | Creates a string from a collection of characters | |
| String.Encoding | Creates a string from data using a specific encoding | |
2. Using String Interpolation (\())
String interpolation in Swift allows you to embed expressions directly into string literals using the \() syntax. This is useful for combining variables, constants, or expressions with literal strings.
| Feature | Description | Example |
|---|---|---|
| Basic Interpolation | Inserts the value of a variable or constant into a string. | |
| Expression Interpolation | Embeds the result of an expression inside a string. | |
| Formatting Interpolation | Allows formatting of numeric values within the string. | |
Example: Combining Multiple Values
let firstName = "John"
let lastName = "Doe"
let age = 30
let message = "User: \(firstName) \(lastName), Age: \(age)"
print(message) // Output: User: John Doe, Age: 30
Note: The expression inside
\() must be a valid Swift expression that evaluates to a type compatible with string interpolation.
3. Concatenating Strings
| Method | Description | Example |
|---|---|---|
| + | Concatenation operator for strings | |
| String.appending() | Appends a string to another string | |
| String(format:) | Formats a string with placeholders | |
| String Interpolation | Inserts values directly into a string literal | |
Note: The
+ operator is not recommended for large-scale string concatenation due to performance implications. Use String.appending() or String(format:) for better efficiency.4. Accessing Characters
| Method | Description | Example |
|---|---|---|
| string[index] | Access character at specific index | |
| string.startIndex | Get index of first character | |
| string.endIndex | Get index after last character | |
| string.index(before:) | Get index before given index | |
| string.index(after:) | Get index after given index | |
| string.index(offsetBy:) | Get index at offset from given index | |
Note: String indices in Swift are not integers but
String.Index types, which allows for proper handling of Unicode characters.Example: Iterating Characters
let greeting = "Hello World"
for char in greeting {
print(char)
}
// Outputs each character on a new line
Example: Character Count
let greeting = "Hello"
let charCount = greeting.count // 5
print("Character count: \(charCount)")
5. Using String Methods
| Method | Description | Example |
|---|---|---|
| uppercased() | Returns a new string with all characters in uppercase | |
| lowercased() | Returns a new string with all characters in lowercase | |
| capitalized | Returns a new string with the first character of each word capitalized | |
| reversed() | Returns a new string with the characters in reverse order | |
| contains(_:) | Checks if a string contains another string | |
| hasPrefix(_:) / hasSuffix(_:) | Checks if a string starts or ends with a specific substring | |
| replacingOccurrences(of:with:) | Replaces all occurrences of a substring with another | |
| trimmingCharacters(in:) | Removes specified characters from the start and end of a string | |
| components(separatedBy:) | Splits a string into an array of substrings based on a delimiter | |
| split(separator:) | Splits a string into an array of substrings using a separator | |
6. Modifying Strings
| Method | Description | Example |
|---|---|---|
| inserting | Inserts a string at a specified index | |
| replacing | Replaces a substring with another string | |
| removing | Removes a substring from a string | |
| trimming | Removes whitespace from both ends of a string | |
7. Splitting and Joining
| Method | Description | Example |
|---|---|---|
| components(separatedBy:) | Splits a string into an array of substrings using a delimiter. | |
| split(separator:) | Splits a string into an array of substrings using a character separator. | |
| joined(separator:) | Joins an array of strings into a single string with a separator. | |
Note:
components(separatedBy:) returns an array of strings, while split(separator:) returns a collection of substrings.8. Working with Substrings
| Property | Description | Example |
|---|---|---|
| substring | Creates a substring from a string using indices | |
| substring(with:) | Extracts a substring using a Range | |
| subscript with indices | Accesses a substring using start and end indices | |
Example: Extracting Substrings
let text = "The quick brown fox jumps over the lazy dog"
let firstWord = String(text[..<text.index(text.startIndex, offsetBy: 3)])
print(firstWord) // "The"
let lastWord = String(text[text.index(text.endIndex, offsetBy: -3)...])
print(lastWord) // "dog"
Example: Using Substring in a Loop
let sentence = "Swift is powerful"
for i in 0..<sentence.count {
let char = sentence[sentence.index(sentence.startIndex, offsetBy: i)]
print(char)
}
9. Using String Formatting
| Format | Description | Example | Result |
|---|---|---|---|
| % | Basic placeholder for any type | String(format: "Value is %d", 42) |
Value is 42 |
| %.2f | Float with 2 decimal places | String(format: "Price: $%.2f", 19.99) |
Price: $19.99 |
| %s | String placeholder | String(format: "Hello %s", "World") |
Hello World |
| %d | Integer placeholder | String(format: "Count: %d", 100) |
Count: 100 |
| %@ | Object placeholder (used in Foundation) | String(format: "Object: %@", someObject) |
Object: <SomeObject> |
Example: String Formatting with Variables
let name = "Alice"
let age = 30
let message = String(format: "Hello, %s! You are %d years old.", name, age)
print(message) // Output: Hello, Alice! You are 30 years old.
Example: Formatting Floating Point Numbers
let price = 123.456
let formattedPrice = String(format: "Price: $%.2f", price)
print(formattedPrice) // Output: Price: $123.46
Note: The
String(format:arguments:) method is part of the Foundation framework and uses C-style format specifiers.
Warning: Format strings are not type-safe. Using incorrect format specifiers can lead to runtime errors or unexpected behavior.
10. Understanding Unicode and Character Sets
| Concept | Description | Notes |
|---|---|---|
| Unicode Scalar Value | Represents a 21-bit Unicode code point, used internally by Swift. | Each scalar value is a unique identifier for a character in the Unicode standard. |
| Character | A Unicode scalar value, represented by the Character type. |
Can be a single character or a grapheme cluster (e.g., an emoji with modifiers). |
| String | A collection of characters, represented by the String type. |
Swift strings are Unicode-compliant and support grapheme clusters natively. |
Example: Unicode Scalar Values
let unicodeScalar = "\u{2603}" // Unicode snowman character
let scalarValue = unicodeScalar.unicodeScalars.first!.value
print(scalarValue) // Output: 9731
Example: Grapheme Clusters
let emojiWithModifier = "๐จโ๐ฉโ๐งโ๐ฆ" // Family emoji with skin tone modifiers
print(emojiWithModifier.count) // Output: 1 (grapheme cluster)
print(emojiWithModifier.unicodeScalars.count) // Output: 5 (scalar values)
Note: Swift strings are not just collections of characters but are designed to handle Unicode grapheme clusters correctly, ensuring that emojis and other complex characters are treated as single units.
11. Using Multi-line Strings
| Property | Description | Example |
|---|---|---|
| Triple Quotes | Used to define multi-line strings in Swift. | |
| Line Continuation | Backslash at end of line to continue string on next line. | |
| String Interpolation | Embed expressions inside string literals using \(). | |