File Handling in Swift

Read from and write to files in Swift, enabling data persistence and retrieval.

File Handling in Swift
Photo by Maxim Hopman / Unsplash

Read from and write to files in Swift, enabling data persistence and retrieval.

let filePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("data.txt")
let dataToWrite = "Hello, File Handling!".data(using: .utf8)
try? dataToWrite?.write(to: filePath)

if let dataRead = try? Data(contentsOf: filePath),
   let fileContents = String(data: dataRead, encoding: .utf8) {
    print("File Contents: \(fileContents)")
}