Swift – Write an Array to a Text File


I read into myArray (native Swift) from a file containing a few thousand lines of plain text..

myData = String.stringWithContentsOfFile(myPath, encoding: NSUTF8StringEncoding, error: nil)
var myArray = myData.componentsSeparatedByString("\n")

I change some of the text in myArray (no point pasting any of this code).

Now I want to write the updated contents of myArray to a new file.
I've tried this ..

let myArray2 = myArray as NSArray
myArray2.writeToFile(myPath, atomically: false)

but the file content is then in the plist format.

Is there any way to write an array of text strings to a file (or loop through an array and append each array item to a file) in Swift (or bridged Swift)?

Best Solution

As drewag points out in the accepted post, you can build a string from the array and then use the writeToFile method on the string.

However, you can simply use Swift's Array.joinWithSeparator to accomplish the same with less code and likely better performance.

For example:

// swift 2.0
let array = [ "hello", "goodbye" ]
let joined = array.joinWithSeparator("\n")
do {
    try joined.writeToFile(saveToPath, atomically: true, encoding: NSUTF8StringEncoding)
} catch {
    // handle error

// swift 1.x
let array = [ "hello", "goodbye" ]
let joined = "\n".join(array)