Reading and Writing Data
Persist Data and strings to disk.
Reading and Writing Data is a free Swift Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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")Reading a String
String(contentsOf:encoding:) loads the file back into memory as text.
import Foundation
let url = URL(fileURLWithPath: "/tmp/hello.txt")
if let text = try? String(contentsOf: url, encoding: .utf8) {
print(text)
}Working with Data
Data(contentsOf:) reads any file as raw bytes, suitable for images, archives, or binary formats.
import Foundation
let url = URL(fileURLWithPath: "/tmp/hello.txt")
if let data = try? Data(contentsOf: url) {
print("Byte count: \(data.count)")
}Writing Data
data.write(to:) persists bytes to a file. Combine with encoding to store text or any serialized payload.
import Foundation
let bytes = Data([0x48, 0x69])
let url = URL(fileURLWithPath: "/tmp/bytes.bin")
try? bytes.write(to: url)
print("Wrote raw data")Data to String
Convert Data to text with String(data:encoding:) when you know the byte encoding.
import Foundation
let data = Data([0x48, 0x69])
if let s = String(data: data, encoding: .utf8) {
print(s)
}Encoding JSON
Use JSONEncoder to turn a Codable value into Data ready to write to disk.
import Foundation
struct Note: Codable { let text: String }
let data = try? JSONEncoder().encode(Note(text: "hi"))
let url = URL(fileURLWithPath: "/tmp/note.json")
try? data?.write(to: url)
print("Saved JSON")Decoding JSON
Read the data back and decode it with JSONDecoder into your model type.
import Foundation
struct Note: Codable { let text: String }
let url = URL(fileURLWithPath: "/tmp/note.json")
if let data = try? Data(contentsOf: url),
let note = try? JSONDecoder().decode(Note.self, from: data) {
print(note.text)
}Atomic Writes
The atomically: true option writes to a temporary file then renames it, so readers never see a half-written file.
import Foundation
let url = URL(fileURLWithPath: "/tmp/safe.txt")
try? "important".write(to: url, atomically: true, encoding: .utf8)
print("Atomic write done")Handling Errors
File operations throw. Use do/catch to react to missing files or permission problems instead of crashing.
import Foundation
let url = URL(fileURLWithPath: "/does/not/exist.txt")
do {
_ = try String(contentsOf: url, encoding: .utf8)
} catch {
print("Read failed: \(error.localizedDescription)")
}Append vs Overwrite
The basic write(to:) overwrites. To append, open a FileHandle and seek to the end before writing.
import Foundation
let url = URL(fileURLWithPath: "/tmp/log.txt")
if let handle = try? FileHandle(forWritingTo: url) {
handle.seekToEndOfFile()
handle.write(Data("line\n".utf8))
try? handle.close()
}
print("Appended")Quick Check
What does atomically: true guarantee when writing?
Recap
You read and wrote text with String(contentsOf:) and write(to:atomically:encoding:), handled raw bytes with Data, persisted models via JSONEncoder/Decoder, used atomic writes, caught errors, and appended with FileHandle. Next: managing directories.
Frequently asked questions
Is the “Reading and Writing Data” lesson free?
Yes — the full text of “Reading and Writing Data” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “Reading and Writing Data”?
Persist Data and strings to disk. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Reading and Writing Data” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- URLs and File Paths
- Reading and Writing Data
- Managing Directories
- App Sandbox Directories