在 Swift 中逐行读取文本文件? [英] Read a text file line by line in Swift?
问题描述
我刚开始学习 Swift.我已经从文本文件中读取了我的代码,并且该应用程序显示了整个文本文件的内容.如何逐行显示并多次调用该行?
I just started learning Swift. I have got my code to read from the text file, and the App displays the content of the entire text file. How can I display line by line and call upon that line multiple times?
TextFile.txt
包含以下内容:
1. Banana
2. Apple
3. pear
4. strawberry
5. blueberry
6. blackcurrant
以下是目前拥有的..
if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
if let content = (data){
TextView.text = content
}
如果有其他方法可以做到这一点,请告诉我.将不胜感激.
If there is another way of doing this please let me know. It would be much appreciated.
推荐答案
Swift 3.0
if let path = Bundle.main.path(forResource: "TextFile", ofType: "txt") {
do {
let data = try String(contentsOfFile: path, encoding: .utf8)
let myStrings = data.components(separatedBy: .newlines)
TextView.text = myStrings.joined(separator: ", ")
} catch {
print(error)
}
}
变量 myStrings
应该是数据的每一行.
The variable myStrings
should be each line of the data.
使用的代码来自:在 iOS SDK 中逐行读取文件 用 Obj- 编写C 和使用 NSString
The code used is from: Reading file line by line in iOS SDK written in Obj-C and using NSString
检查以前版本的 Swift 的编辑历史.
Check edit history for previous versions of Swift.
这篇关于在 Swift 中逐行读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!