Write to a File in Swift2

Swift2 came out yesterday! For free! I thought that Swift2 would have built-in support for I/O, but it looks like you need to import Cocoa first.

import Cocoa

let data = NSString( string:"Hallo, Welt!" )
let destPath = "/Users/connorjohnson/myFile.txt"
var filemgr = NSFileManager.defaultManager()
do {
    try data.writeToFile(destPath, atomically: true, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
    print("Error: \(error)")
}

Leave a Reply

Your email address will not be published. Required fields are marked *