这个问题已经在这里有一个答案:
基本上,我想与斯威夫特3做到这一点:
write a titleString to file
For i=1 to n
newString = createNewString() //these may look like "1: a, b, c"
append each new string to end of file
next i
这是我做了什么:
let fileURL = URL(fileURLWithPath: completePath)
let titleString = "Line, Item 1, Item 2, Item 3"
var dataString: String
let list1 = [1, 2, 3, 4, 5]
let list2 = ["a", "b", "c", "d", "e"]
let list3 = ["p", "q", "r", "s", "t"]
for i in 0...4 {
dataString = String(list1[i]) + ": " + list2[i] + list3[i] + "\n"
//Check if file exists
if let fileHandle = FileHandle(forReadingAtPath: fileURL.absoluteString) {
fileHandle.seekToEndOfFile()
fileHandle.write(dataString.data(using: .utf8)!)
} else { //create new file
do {
try titleString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch let error as NSError {
print("Error creating file \(error)")
}
}
print(dataString)
print("Saving data in: \(fileURL.path)")
}
所有我在文件中得到的是titleString。其他字符串显示不出来。
您可以使用FileHandle
检查,如果该文件已经存在,后追加现有的文件。
let titleString = "Line, Item 1, Item 2, Item 3"
var dataString: String
let list1 = [1, 2, 3, 4, 5]
let list2 = ["a", "b", "c", "d", "e"]
let list3 = ["p", "q", "r", "s", "t"]
do {
try "\(titleString)\n".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
print(error)
}
for i in 0...4 {
dataString = String(list1[i]) + ": " + list2[i] + list3[i] + "\n"
//Check if file exists
do {
let fileHandle = try FileHandle(forWritingTo: fileURL)
fileHandle.seekToEndOfFile()
fileHandle.write(dataString.data(using: .utf8)!)
fileHandle.closeFile()
} catch {
print("Error writing to file \(error)")
}
print(dataString)
print("Saving data in: \(fileURL.path)")
}
输出:
Line, Item 1, Item 2, Item 3
1: ap
2: bq
3: cr
4: ds
5: et