Write a UTF-8 text file
Save text using an atomic replacement.
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.