Write String to file in Swift

Last Updated: October 15, 2017

First you define the String object and next call the writeToFile() let home = FileManager.default.homeDirectoryForCurrentUser let playgroundPath = “Documents/dev/xcode/DatePicker/c” // Get your playground URL let playgroundURL = home.appendingPathComponent(playgroundPath) let text = “This is the text for the file” let newFile = playgroundURL.appendingPathComponent(“test.txt”) // First create a FileManager instance let fileManager = FileManager.default let path = playgroundURL.path do{ try text.write(to: newFile, atomically: true, encoding: String.Encoding.utf8) } catch { print(“Error”) }