I'd had a hard time getting this to work. I’d like to parse a file containing data and copy this data into a struct.
The data file (test.dat
) looks like this:
1,"Tom","Smith"
2,"Peter","Perth Junior"
3,"Cathy","Johnson"
I use the following function.
func parseDataFile() {
struct person {
var id: Int
var first: String
var last: String
}
var friends: [person] = []
let filePath = Bundle.main.path(forResource: "test", ofType: "dat")
guard filePath != nil else { return }
let fileURL = URL(fileURLWithPath: filePath!)
do {
let file = try String(contentsOf: fileURL, encoding: .utf8)
let arrayOfLines = file.split { $0.isNewline }
for line in arrayOfLines {
let arrayOfItems = line.components(separatedBy: ",")
let tempPerson = person(id: Int(arrayOfItems[0])!,
first: arrayOfItems[1].replacingOccurrences(of: "\"", with: ""),
last: arrayOfItems[2].replacingOccurrences(of: "\"", with: "")
)
friends.append(tempPerson)
}
} catch {
print(error)
}
}
I read the data into a string, split it up into an array (every line is a record). The records are copied into the struct person
. This works fine, but I'm sure this is far from optimum.
I was testing a lot with PropertyListDecoder().decode()
, but this seems to accept only dictionary formatted data (not sure though ?!).
Next, is it necessary to use an array record, as intermediate step, prior putting the line into a struct?
Last, is there no method to copy all comma separated strings to an array, without filling every property of the struct individually (like I did)?
Besides that, I believe that there is also a much more efficient way to get rid of the string delimiting quotes than using replacingOccurrences(of:with:)
?
Any comments would be appreciated.