I'm doing something vaguely similar. My tables are stored as CSV files and loaded at startup like this:
struct Table {
let id: String
let table: [[Double]]
}
enum LoadError: Swift.Error {
case missingTable(String)
}
private var tables = [Table]() // used only in one program file
func loadTables() {
guard tables.count==0 else { return } // don't do it again
do {
for i in 1...18 {
try tables.append(loadTable("t\(i)"))
}
for i in ["a", "b", "c", "d", "em", "ef", "fm", "ff"] {
try tables.append(loadTable(i))
}
for i in ["atf-0.25", "atf-0.75", "atf0", "atm-0.25", "atm-0.75", "atm0"] {
try tables.append(loadTable(i))
}
} catch LoadError.missingTable(let t) {
fatalError("Can't load table \(t)")
} catch {
fatalError("Unexpected error loading tables: \(error)")
}
}
private func loadTable(_ t: String) throws -> Table {
guard let tableURL = Bundle.main.url(forResource: t, withExtension: "txt", subdirectory: "tables"),
let rawText = try? String(contentsOf: tableURL)
else { throw LoadError.missingTable(t) }
let lines = rawText.components(separatedBy: "\n")
var table = [[Double]]()
for j in 0..<lines.count where lines[j].count>1 {
let ageRow = lines[j].components(separatedBy: ",")
let ageRowDouble = ageRow.map { Double($0) ?? 0 }
table.append(ageRowDouble)
}
return (Table(id: t, table: table))
}
It's not awfully efficient, and as this is my first Swift program there may be a better way to do it, but it takes no noticeable time (on an iPhone 8) to load the 32 tables and convert the Strings to Doubles. The tables differ in size: the largest is 125 x 125 (they're the Ogden Tables, published by the UK Government, FWIW, which I've converted from Excel to CSV; this means that I know that simple decoding by comma-separation will work).
Jeremy
PS: this seems more of a Swift than a SwiftUI question, so you might be better off asking in the other forum.