Swift - Write an Array to a Text File

可紊 提交于 2020-01-22 12:19:02

问题


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


回答1:


You need to reduce your array back down to a string:

var output = reduce(array, "") { (existing, toAppend) in
    if existing.isEmpty {
        return toAppend
    }
    else {
        return "\(existing)\n\(toAppend)"
    }
}
output.writeToFile(...)

The reduce method takes a collection and merges it all into a single instance. It takes an initial instance and closure to merge all elements of the collection into that original instance.

My example takes an empty string as its initial instance. The closure then checks if the existing output is empty. If it is, it only has to return the text to append, otherwise, it uses String Interpolation to return the existing output and the new element with a newline in between.

Using various syntactic sugar features from Swift, the whole reduction can be reduced to:

var output = reduce(array, "") { $0.isEmpty ? $1 : "\($0)\n\($1)" }



回答2:


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(...)



回答3:


Swift offers numerous ways to loop through an array. You can loop through the strings and print to a text file one by one. Something like so:

for theString in myArray {
    theString.writeToFile(myPath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
}


来源:https://stackoverflow.com/questions/24977139/swift-write-an-array-to-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!