Swift:
Reading a text file
How to:
To read text from a file in Swift, use String
class’ convenience methods. Here’s a bite-sized example:
import Foundation
if let filePath = Bundle.main.path(forResource: "example", ofType: "txt") {
do {
let content = try String(contentsOfFile: filePath, encoding: .utf8)
print(content)
} catch {
print("Oops! Something went wrong: \(error)")
}
}
If “example.txt” contains “Hello, world!”, the output is:
Hello, world!
Deep Dive
Reading text files is as old as hills in the programming world. Early on, it was all about punch cards and tape. Now, with high-level languages like Swift, it’s straightforward. The snippet above uses String(contentsOfFile:)
, but there are alternatives:
FileManager
: Good for more complex file operations.InputStream
: Use it when dealing with large files—less memory-intensive.URLSession
: Fetch files from a remote server.
The String(contentsOfFile:)
approach can be memory-heavy if used with mega-sized files. To prevent issues, consider stream-based methods or chunked reading.
See Also
Dive into Swift’s official documentation:
For deeper understanding, check out these resources: