Files ยท SWIFT RECIPE

Write a UTF-8 text file

Save text using an atomic replacement.

main.swift
import Foundation
let file = URL(fileURLWithPath: "example.txt")
do {
    try "Hello, Swift!".write(to: file, atomically: true, encoding: .utf8)
    print(try String(contentsOf: file, encoding: .utf8))
} catch { print("Write failed: \(error)") }

How it works

An atomic write uses an intermediate file before replacement, reducing the risk of partial content. Your process needs write permission for the target directory.

EXPECTED OUTPUT
Hello, Swift!

Keep in mind

Online sandbox files are temporary. Download this code to work with your own files.

Read the Swift language reference