Skip to main content

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
let charArray = ["H", "i"]
let stringFromArray = String(charArray)
String.Encoding Creates a string from data using a specific encoding
let data = "Hello".data(using: .utf8)!
let stringFromData = String(data: data, encoding: .utf8)

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.
let name = "Alice"
let greeting = "Hello, \(name)!"
print(greeting) // Output: Hello, Alice!
Expression Interpolation Embeds the result of an expression inside a string.
let x = 5
let y = 10
let sum = "The sum of \(x) and \(y) is \(x + y)."
print(sum) // Output: The sum of 5 and 10 is 15.
Formatting Interpolation Allows formatting of numeric values within the string.
let pi = 3.14159
let formattedPi = "Pi is approximately \(String(format: "%.2f", pi))"
print(formattedPi) // Output: Pi is approximately 3.14

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
let str1 = "Hello"
let str2 = "World"
let result = str1 + " " + str2
// "Hello World"
String.appending() Appends a string to another string
var greeting = "Hello"
greeting.append(" World")
// "Hello World"
String(format:) Formats a string with placeholders
let name = "Alice"
let age = 30
let message = String(format: "Hello %s, you are %d years old", name, age)
// "Hello Alice, you are 30 years old"
String Interpolation Inserts values directly into a string literal
let item = "book"
let count = 5
let sentence = "I have \(count) \(item)s."
// "I have 5 books."
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
let greeting = "Hello"
let firstChar = greeting[0] // "H"
string.startIndex Get index of first character
let greeting = "Hello"
let firstIndex = greeting.startIndex // Index of "H"
string.endIndex Get index after last character
let greeting = "Hello"
let lastIndex = greeting.endIndex // Index after "o"
string.index(before:) Get index before given index
let greeting = "Hello"
let beforeLast = greeting.index(before: greeting.endIndex)
let lastChar = greeting[beforeLast] // "o"
string.index(after:) Get index after given index
let greeting = "Hello"
let afterFirst = greeting.index(after: greeting.startIndex)
let secondChar = greeting[afterFirst] // "e"
string.index(offsetBy:) Get index at offset from given index
let greeting = "Hello"
let thirdIndex = greeting.index(greeting.startIndex, offsetBy: 2)
let thirdChar = greeting[thirdIndex] // "l"
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
let greeting = "hello world"
let upper = greeting.uppercased()
print(upper) // "HELLO WORLD"
lowercased() Returns a new string with all characters in lowercase
let greeting = "HELLO WORLD"
let lower = greeting.lowercased()
print(lower) // "hello world"
capitalized Returns a new string with the first character of each word capitalized
let phrase = "hello world"
let capitalized = phrase.capitalized
print(capitalized) // "Hello World"
reversed() Returns a new string with the characters in reverse order
let word = "swift"
let reversed = String(word.reversed())
print(reversed) // "tfwsi"
contains(_:) Checks if a string contains another string
let sentence = "The quick brown fox"
let hasFox = sentence.contains("fox")
print(hasFox) // true
hasPrefix(_:) / hasSuffix(_:) Checks if a string starts or ends with a specific substring
let fileName = "document.pdf"
let isPDF = fileName.hasSuffix(".pdf")
let isDoc = fileName.hasPrefix("document")
print(isPDF) // true
print(isDoc) // true
replacingOccurrences(of:with:) Replaces all occurrences of a substring with another
let text = "Hello world, world!"
let replaced = text.replacingOccurrences(of: "world", with: "Swift")
print(replaced) // "Hello Swift, Swift!"
trimmingCharacters(in:) Removes specified characters from the start and end of a string
let spaced = "  hello world  "
let trimmed = spaced.trimmingCharacters(in: .whitespaces)
print(trimmed) // "hello world"
components(separatedBy:) Splits a string into an array of substrings based on a delimiter
let csvLine = "apple,banana,cherry"
let fruits = csvLine.components(separatedBy: ",")
print(fruits) // ["apple", "banana", "cherry"]
split(separator:) Splits a string into an array of substrings using a separator
let sentence = "one two three"
let words = sentence.split(separator: " ")
print(words) // ["one", "two", "three"]

6. Modifying Strings

Method Description Example
inserting Inserts a string at a specified index
var str = "Hello"
str.insert(" World", at: str.index(str.startIndex, offsetBy: 5))
print(str) // "Hello World"
replacing Replaces a substring with another string
let str = "Hello World"
let newStr = str.replacingOccurrences(of: "World", with: "Swift")
print(newStr) // "Hello Swift"
removing Removes a substring from a string
let str = "Hello World"
let newStr = str.replacingOccurrences(of: "World", with: "")
print(newStr) // "Hello "
trimming Removes whitespace from both ends of a string
let str = "  Hello World  "
let trimmedStr = str.trimmingCharacters(in: .whitespaces)
print(trimmedStr) // "Hello World"

7. Splitting and Joining

Method Description Example
components(separatedBy:) Splits a string into an array of substrings using a delimiter.
let sentence = "Hello, world, Swift"
let words = sentence.components(separatedBy: ", ")
print(words) // ["Hello", "world", "Swift"]
split(separator:) Splits a string into an array of substrings using a character separator.
let text = "one-two-three"
let parts = text.split(separator: "-")
print(parts) // ["one", "two", "three"]
joined(separator:) Joins an array of strings into a single string with a separator.
let words = ["Hello", "world", "Swift"]
let sentence = words.joined(separator: " ")
print(sentence) // "Hello world Swift"
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
let str = "Hello, World!"
let sub = str[..<str.index(str.startIndex, offsetBy: 5)]
print(sub) // "Hello"
substring(with:) Extracts a substring using a Range
let str = "Swift Programming"
let range = str.range(of: "Programming")!
let sub = str[range]
print(sub) // "Programming"
subscript with indices Accesses a substring using start and end indices
let str = "iOS Development"
let start = str.index(str.startIndex, offsetBy: 4)
let end = str.index(str.startIndex, offsetBy: 13)
let sub = String(str[start..<end])
print(sub) // "Development"

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.
let multilineString = """
This is line 1.
This is line 2.
This is line 3.
"""
Line Continuation Backslash at end of line to continue string on next line.
let continuedString = "This is line 1. \
This is line 2."
String Interpolation Embed expressions inside string literals using \().
let name = "John"
let age = 30
let interpolatedString = "Hello, \(name)! You are \(age) years old."

Example: Multi-line String with Interpolation

let message = """
    Welcome, \(name)!
    Today is \(Date().formatted(date: .complete, time: .omitted)).
    You have \(10) unread messages.
"""

Was this article helpful?