Reading and Writing Data
Persist Data and strings to disk.
Reading and Writing Data
Foundation's Data type holds raw bytes, and String plus Data both know how to read from and write to file URLs.
Writing a String
write(to:atomically:encoding:) saves a string to a file URL. Atomic writes use a temp file to avoid corruption.
import Foundation
let url = URL(fileURLWithPath: "/tmp/hello.txt")
try? "Hello, file!".write(to: url, atomically: true, encoding: .utf8)
print("Wrote string to disk")All lessons in this course
- URLs and File Paths
- Reading and Writing Data
- Managing Directories
- App Sandbox Directories