Here's a revised Example App for your situation, where there's now a Search Bar and only search results are shown in the View - not the full set of Terms and Phrases.
ContentView
import SwiftUI
import TabularData
struct ContentView: View {
@ObservedObject var model = DataModel.shared
@State private var searchText = ""
var body: some View {
NavigationView{
Text("Searching for \(searchText)")
.searchable(text: $searchText)
List(model.searchResults.rows,id:\.index) { row in
HStack{
Text(row["Term"] as! String)
Text(String(row["Phrase"] as! String))
}
}
}
.onChange(of: searchText) { srchText in
model.searchResults = model.findTerm(srchText)
}
}
}
Data Model
import Foundation
import TabularData
class DataModel : ObservableObject {
static let shared = DataModel()
var dataTable = DataFrame()
@Published var searchResults = DataFrame()
init() {
getData()
}
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 get load datatable from CSV \(error)")
return
}
}
func findTerm(_ searchTerm: String) -> DataFrame {
let results = dataTable.filter ({ row in
guard let term = row["Term"] as? String else {
return false
}
if term == searchTerm {
return true
}
return false
})
return DataFrame(results)
}
}
extension DataFrame.Rows : RandomAccessCollection {
}
Caution!!
The findTerm func checks for an exact match of the Term, i.e. case sensitive and full match. If you need case insensitivity and partial matches, you need to change the findTerm function.
If your purpose is only to look up phrases for a Term, then this is pretty much a complete solution, although if you've started an Xcode project with View Controllers (Storyboard) then to use my solution you'll need to create a new project with SwiftUI Interface.
Best wishes and regards, Michaela
Topic:
Programming Languages
SubTopic:
Swift
Tags: