Files ยท SWIFT RECIPE

Read a UTF-8 text file

Read a file and handle filesystem errors.

main.swift
import Foundation
let file = URL(fileURLWithPath: "example.txt")
do {
    print(try String(contentsOf: file, encoding: .utf8))
} catch { print("Read failed: \(error)") }

How it works

This synchronous initializer reads the whole file and decodes UTF-8. It throws for missing files, permissions, and decoding failures.

Keep in mind

Create example.txt first. Stream very large files instead of loading the entire content.

Read the Swift language reference