Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 742
Kym Avatar asked Jul 27 '14 01:07

Kym


2 Answers

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)
joined.writeToFile(...)
like image 132
DPlusV Avatar answered Sep 26 '22 02:09

DPlusV


With Swift 5 and I guess with Swift 4 you can use code snippet which works fine to me.

let array = ["hello", "world"]
let joinedStrings = array.joined(separator: "\n")

do {
    try joinedStrings.write(toFile: outputURL.path, atomically: true, encoding: .utf8)
} catch let error {
    // handle error
    print("Error on writing strings to file: \(error)")
}
like image 30
abdullahselek Avatar answered Sep 23 '22 02:09

abdullahselek