How to write data to file in Swift

Last Updated: October 16, 2017

In this example you can see how to write some data to the text file. I am using XCODE playground to test this code

let home = FileManager.default.homeDirectoryForCurrentUser
let playgroundPath = "Documents/dev/xcode/DatePicker/c"

// get your playground URL
let playgroundURL = home.appendingPathComponent(playgroundPath)

let newFile = playgroundURL.appendingPathComponent("test.txt").path

let file: FileHandle? = FileHandle(forWritingAtPath: newFile)

if file != nil {
    // You can make the data
    let data = ("Some Text to write" as String).data(using: String.Encoding.utf8)
    // Write it to the file
    // Close the file
else {
    print("Ooops! Something went wrong!")

Alternatively you can define the text first and the you can use writeToFile() method