Swift Standard Library
Essential types and functions built into Swift
📚 What is the Swift Standard Library?
The Swift Standard Library provides fundamental types, protocols, and functions that form the foundation of Swift programming. It includes collections, strings, numbers, and essential algorithms available in every Swift program.
// Standard Library types you use every day
let numbers = [1, 2, 3, 4, 5] // Array
let name = "Swift" // String
let age = 25 // Int
let isActive = true // Bool
// Built-in methods
let doubled = numbers.map { $0 * 2 }
let greeting = "Hello, \(name)!"
Core Standard Library Types
Strings
Text manipulation and processing
let text = "Hello, World!"
let uppercase = text.uppercased()
let contains = text.contains("World")
Collections
Arrays, Sets, and Dictionaries
let array = [1, 2, 3]
let set: Set = [1, 2, 3]
let dict = ["key": "value"]
Numbers
Integer and floating-point types
let integer: Int = 42
let double: Double = 3.14159
let float: Float = 2.5
Optionals
Safe handling of nil values
let optional: String? = "Hello"
let unwrapped = optional ?? "Default"
🔹 Working with Arrays
Arrays are ordered collections with powerful built-in methods:
var fruits = ["apple", "banana", "orange"]
// Adding elements
fruits.append("grape")
fruits.insert("mango", at: 1)
// Accessing elements
let first = fruits.first // Optional("apple")
let last = fruits.last // Optional("grape")
let second = fruits[1] // "mango"
// Array operations
let count = fruits.count
let isEmpty = fruits.isEmpty
let contains = fruits.contains("banana")
// Functional programming methods
let uppercased = fruits.map { $0.uppercased() }
let filtered = fruits.filter { $0.count > 5 }
let sorted = fruits.sorted()
// Reducing to a single value
let concatenated = fruits.reduce("") { result, fruit in
result + fruit + " "
}
print(fruits) // ["apple", "mango", "banana", "orange", "grape"]
print(uppercased) // ["APPLE", "MANGO", "BANANA", "ORANGE", "GRAPE"]
🔹 String Manipulation
Strings have rich functionality for text processing:
let message = " Hello, Swift World! "
// Basic operations
let length = message.count
let uppercase = message.uppercased()
let lowercase = message.lowercased()
let trimmed = message.trimmingCharacters(in: .whitespaces)
// String interpolation
let name = "Alice"
let age = 30
let greeting = "Hello, \(name)! You are \(age) years old."
// Checking content
let startsWithHello = message.hasPrefix(" Hello")
let endsWithExclamation = message.hasSuffix("!")
let containsSwift = message.contains("Swift")
// String splitting and joining
let words = message.components(separatedBy: " ")
let rejoined = words.joined(separator: "-")
// Character iteration
for char in "Swift" {
print(char) // S, w, i, f, t
}
print(trimmed) // "Hello, Swift World!"
print(words) // ["", "", "Hello,", "Swift", "World!", "", ""]
🔹 Dictionaries and Sets
Key-value pairs and unique collections:
// Dictionary operations
var scores = ["Alice": 95, "Bob": 87, "Charlie": 92]
// Adding and updating
scores["David"] = 88
scores["Alice"] = 97 // Update existing
// Accessing values
let aliceScore = scores["Alice"] // Optional(97)
let eveScore = scores["Eve"] ?? 0 // Default value
// Dictionary methods
let keys = Array(scores.keys)
let values = Array(scores.values)
let isEmpty = scores.isEmpty
// Set operations
let colors1: Set = ["red", "blue", "green"]
let colors2: Set = ["blue", "yellow", "green"]
// Set operations
let union = colors1.union(colors2)
let intersection = colors1.intersection(colors2)
let difference = colors1.subtracting(colors2)
// Set methods
let contains = colors1.contains("red")
colors1.insert("purple")
colors1.remove("blue")
print(scores) // ["Alice": 97, "Bob": 87, "Charlie": 92, "David": 88]
print(intersection) // {"blue", "green"}
🔹 Ranges and Sequences
Working with ranges and sequence operations:
// Different types of ranges
let closedRange = 1...5 // 1, 2, 3, 4, 5
let halfOpenRange = 1..<5 // 1, 2, 3, 4
let partialRange = 3... // 3 to infinity
// Using ranges with arrays
let numbers = [10, 20, 30, 40, 50]
let subset = Array(numbers[1...3]) // [20, 30, 40]
// Range operations
for i in 1...3 {
print("Number: \(i)")
}
// Sequence operations
let sequence = stride(from: 0, to: 10, by: 2) // 0, 2, 4, 6, 8
let reversed = (1...5).reversed() // 5, 4, 3, 2, 1
// Zip sequences together
let names = ["Alice", "Bob", "Charlie"]
let ages = [25, 30, 35]
let pairs = zip(names, ages)
for (name, age) in pairs {
print("\(name) is \(age) years old")
}
// Enumerated sequences
for (index, value) in ["a", "b", "c"].enumerated() {
print("Index \(index): \(value)")
}
🔹 Error Handling
Swift's built-in error handling mechanisms:
// Define custom errors
enum ValidationError: Error {
case tooShort
case tooLong
case invalidCharacters
}
// Function that can throw
func validatePassword(_ password: String) throws -> Bool {
if password.count < 8 {
throw ValidationError.tooShort
}
if password.count > 50 {
throw ValidationError.tooLong
}
let allowedCharacters = CharacterSet.alphanumerics
if password.rangeOfCharacter(from: allowedCharacters.inverted) != nil {
throw ValidationError.invalidCharacters
}
return true
}
// Using do-catch
do {
let isValid = try validatePassword("mypassword123")
print("Password is valid: \(isValid)")
} catch ValidationError.tooShort {
print("Password is too short")
} catch ValidationError.tooLong {
print("Password is too long")
} catch ValidationError.invalidCharacters {
print("Password contains invalid characters")
} catch {
print("Unknown error: \(error)")
}
// Optional try
let result = try? validatePassword("abc") // nil if throws
let forcedResult = try! validatePassword("validpassword123") // Crashes if throws
🔹 Standard Library Best Practices
Tips for effective use of the Standard Library:
✅ Do:
- Use higher-order functions like map, filter, reduce
- Leverage string interpolation for readable code
- Use optionals safely with nil coalescing and optional binding
- Choose the right collection type for your use case
- Use ranges for efficient subsequence operations
❌ Don't:
- Force unwrap optionals unless absolutely necessary
- Use arrays when sets would be more appropriate
- Ignore error handling in throwing functions
- Mutate collections while iterating over them