Write string to file


I have a string and want to write its contents to a specific file.


// Set the file path
let path = "myfile.txt"

// Set the contents
let contents = "Here are my file's contents"

do {
    // Write contents to file
    try contents.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
catch let error as NSError {
    print("Ooops! Something went wrong: \(error)")


Find answers here

Hi there! Ask Us a Question We are ready to help