Very new to all this but I'm trying to make an excel document work as almost a dictionary where in the first column becomes the key for the answer in the next column. I found something on a different forum that I couldn't understand but it also seems more complex than what I'm trying to do.
I guess I have 3 questions.
-
Does a database have to be on the cloud or does it just refer to a literally
-
If i have 200 terms i want to link to 200 phrases do all of those have to be actually in the code or can the code just be told to read an excel or excel type document and setup a dictionary accordingly.
-
Does this need to be a dictionary or a database and what is the difference? (The only other small point is whether dictionaries can have one key linked to many answers)
The code I previously found is linked here
var theDatabase = YourDatabase() // whatever is your database model
// read the file as one big string var fileContents:String do { fileContents = try String(contentsOfFile: destinationPath, encoding: String.Encoding.utf8) } catch let error { print("Error reading file: (error.localizedDescription)") fileContents = "" }
guard fileContents.count>0 else { return theDatabase }
// split out records (separated by returns) let records = fileContents.split { $0 == "\r" }
// first record is field names, i.e., column titles let fieldNames = findFields(String(records[0]))
// all remaining records are data, so match each with field names of record 0 for k in 1..<records.count { let values = findFields(String(records[k])) var dictionary = [String:String ])() // the first close bracket immediately above was needed to post on forum not in actual code for n in 0..<values.count { dictionary[fieldNames[n]] = values[n] } theDatabase.append(dictionary) // append would be a method in YourDatabase }
credit - DelawareMathGuy
https://developer.apple.com/forums/thread/124621
Any help would be much appreciated
The answers to your questions depend what you want to do with the "Dictionary", how volatile it is (i.e. updates, additions, deletions) and how large it is. A few hundred Terms that never change could be handled without a database (i.e. without an indexed, structured permanent store such as SQLite or CoreData). From my understanding of what you're looking for, I'd suggest creating your terms/phrases in a spreadsheet (e.g. Excel) and then exporting the table as a CSV file for use with code like in the SwiftUI sample below:
ContentView
import SwiftUI
import TabularData
struct ContentView: View {
var model = DataModel.shared
var body: some View {
List(model.dataTable.rows,id:\.index) { row in
HStack{
Text(row["Term"] as! String)
Text(String(row["Phrase"] as! String))
}
}
}
}
Data Model - this is not a database: it's where the importing and processing of the terms takes place within the app, and the data have to be loaded into the app again when next run.
import Foundation
import TabularData
class DataModel {
static let shared = DataModel()
@Published var dataTable = DataFrame()
init() {
getData()
let searchTerm = "Nine"
print("there are \(findTerm(searchTerm).rows.count) terms for \(searchTerm)")
}
func getData() {
var url: URL?
do {
url = try FileManager.default.url(for: FileManager.SearchPathDirectory.downloadsDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: true)
} catch {
print("Failed to get Downsloads URL \(error)")
return
}
let csvOptions = CSVReadingOptions(hasHeaderRow: true, ignoresEmptyLines: true, delimiter: ",")
let fileURL = url?.appendingPathComponent("TermPhrases.csv")
do {
dataTable = try DataFrame(contentsOfCSVFile: fileURL!,columns: nil, rows: nil, types: ["Term":CSVType.string,"Phrase":CSVType.string], options: csvOptions)
} catch {
print("Failed to load datatable from CSV \(error)")
return
}
}
func findTerm(_ searchTerm: String) -> DataFrame.Slice {
let results = dataTable.filter ({ row in
guard let term = row["Term"] as? String else {
return false
}
if term == searchTerm {
return true
}
return false
})
return results
}
}
extension DataFrame.Rows : RandomAccessCollection {
}
Thiis sample uses the TabularData Framework which has many features for importing and manipulating data from CSV files (spreadsheet output), but also for Machine Learning. This sample app was written for MacOS using csv input from the Downloads folder:
Sample Data in a file called TermPhrases.csv
Term Phrase
Nine A stitch in time saves these
Two A bird in the hand is worth these in the bush
Seven Pillars of wisdom
The findTerm function in the DataModel shows how to filter (Search) the Data Table for a term. DataFrame filtering is not like normal Swift array filtering.
Hopefully this gets you started, then you can decide what other processing you'd like to do on the Data Table (i.e. your dictionary)
Best wishes and regards, Michaela