斯威夫特 - 写一个数组到文本文件 [英] Swift - Write an Array to a Text File

查看:156
本文介绍了斯威夫特 - 写一个数组到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从包含纯文本几千行的文件读入myArray的(本地斯威夫特)。

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

我改变一些在myArray的(没有点任何粘贴此code)的文本。

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

现在我想myArray的更新后的内容写入新文件。
我试过这个..

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)

但该文件的内容是那么的plist中的格式。

but the file content is then in the plist format.

有没有办法写文本字符串数组到一个文件中(通过一个数组或循环,每个数组项附加到文件)的斯威夫特(或桥接SWIFT)?

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

推荐答案

您需要背下来减少数组的字符串:

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.

我的例子接受一个空字符串作为其初始实例。闭合然后检查如果现有的输出为空。如果是,它只有返回到追加的文字,否则,它使用<一个href=\"https://developer.apple.com/library/$p$prelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-XID_420\"相对=nofollow>字符串插值返回之间现有的产出和新元素以换行符。

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)" }

这篇关于斯威夫特 - 写一个数组到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆