0Pricing
Swift Academy · Lesson

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

  1. URLs and File Paths
  2. Reading and Writing Data
  3. Managing Directories
  4. App Sandbox Directories
← Back to Swift Academy