[英]Reading a text file and returning a array of dictionary in swift
我正在嘗試讀取文本文件並返回 swift 中的字典數組
文本文件包含以下數據:
13582;Name 1;12345;5
13583;Name 2;23456;5
13585;Name 3;EX934;6
13598;Name 4;XE345_c;6
13600;Name 5;XF8765;6
func machineNumberToName() -> [[String: String]] {
var dic1 = [String: String]()
var dic2 = [String: String]()
var dic3 = [String: String]()
var dic4 = [String: String]()
// FileName for machines
let fileName = "Machines.txt";
if let path = Bundle.main.path(forResource: fileName, ofType: nil) {
do {
let contents = try! String(contentsOfFile: path)
let lines = contents.split(separator: "\n")
for line in lines {
var entries = lines.split(separator: ";")
dic1["machineNumber"] = entries[0]
dic2["machineName"] = entries[1]
dic3["machineXML"] = entries[2]
dic4["wifi"] = entries[3]
return [dic1, dic2, dic3, dic4]
}
} catch {
print(error.localizedDescription)
}
} else {
NSLog("file not found: \(fileName)")
return []
}
}
但是我得到了錯誤
Cannot assign value of type 'Array<String.SubSequence>.SubSequence' (aka 'ArraySlice<Substring>') to subscript of type 'String'
不知道我做錯了什么!
entries
不是String
的數組,它是ArraySlice<Substring>
的數組,或者非正式的子字符串數組。
您可以使用String(entries[0])
獲取要放入字典的字符串。
不過,您還有另一個問題; 你只會得到字典中的第一行,因為你return
了循環。 即使你解決了這個問題,返回一個字典數組也很麻煩。 創建一個適當的結構並返回這些結構的數組
struct MachineDetails {
let machineNumber: String
let machineName: String
let machineXML: String
let machineWiFi: String
}
func getMachineDetails() -> [MachineDetails] {
var details = [MachineDetails]()
let fileName = "Machines.txt";
if let path = Bundle.main.path(forResource: fileName, ofType: nil) {
do {
let contents = try String(contentsOfFile: path)
let lines = contents.split(separator: "\n")
for line in lines {
let entries = line.split(separator: ";").map { String($0) }
if entries.count == 4 {
let newMachine = MachineDetails(machineNumber:entries[0],
machineName:entries[1],
machineXML:entries[2],
machineWiFi:entries[3])
details.append(newMachine)
} else {
print("Malformed line \(line)")
}
}
} catch {
print(error.localizedDescription)
}
} else {
NSLog("file not found: \(fileName)")
}
return details
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.