我想知道什么是最好的方法来获取包含以下格式行的文本文件:姓:名:猫的数量:狗的数量:鱼的数量:其他宠物的数量
并生成包含以下格式行的文本文件:
名字姓氏:宠物总数
例如,它将使用包含以下内容的文本文件:
Apple:Tim:0:0:3:0
Jobs:Steve:0:0:5:2
Da Kid:Billie:0:1:0:1
White:Walter:2:1:1:0
Bond:James:2:2:3:0
Stark:Tony:0:1:2:0
Wayne:Bruce:0:0:0:0
并输出一个文本文件,如下所示:
Tim Apple:3
Steve Jobs:7
Bille Da Kid:2
Walter White:4
James Bond:7
Tony Stark:3
Bruce Wayne:0
以下是我一直在尝试但没有成功的方法:
let namesFile = "Names"
let dir = try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask, appropriateFor: nil, create: true)
// If the directory was found, we write a file to it and read it back
if let fileURL = dir?.appendingPathComponent(namesFile).appendingPathExtension("txt") {
print (fileURL)
var petSum = 0;
do {
let entriesString = try String(contentsOf: fileURL)
let entries = entriesString.components(separatedBy: "\n")
for entry in entries {
let namePets = entry.components(separatedBy: ":")
if (namePets.indices.contains(1)) {
var sum = 0;
print(namePets[1])
print(namePets[0])
for namePet in namePets {
if let intArg = Int(namePet) {
sum = sum + intArg
}
}
print (sum)
print ("\n")
}
}
} catch {
print("Failed reading from URL, Error: " + error.localizedDescription)
}
}
else {
print("didn't work")
}
/*
// Read from the file
var inString = ""
// Write to the file named Test
let outString = "Write this text to the file"
do {
try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
*/
会很感激任何帮助,谢谢!
1条答案
按热度按时间6rqinv9w1#
Int
,并将它们相加。