问题
Hello i'm try to search an airport in a big list of item create from an Array called airportVector of type AirportModel, but when I try to lunch the search as soon I type the first letter everything block! looks like the list is too big .
if I leave only few item the list work.
I tried to make my model conform to Equatable and Hashable but i'm not to expert how to use it.. look for some help or suggestion how to avoid the block.
here my model
import Foundation
class AirportModel : Identifiable , Codable, Equatable, Hashable {
var id : UUID = UUID()
var aptICAO : String
var aptName : String
var aptCity : String
var aptCountry :String
var aptIATA : String
func hash(into hasher: inout Hasher) {
hasher.combine(aptICAO)
}
init(aptICAO: String, aptName: String, aptCity: String, aptCountry: String, aptIATA: String) {
self.aptICAO = aptICAO
self.aptName = aptName
self.aptCity = aptCity
self.aptCountry = aptCountry
self.aptIATA = aptIATA
}
static func == (lhs: AirportModel,rhs: AirportModel) -> Bool{
return lhs.aptICAO == rhs.aptICAO
}
}
here my View with the searcher
import SwiftUI
struct AirportView: View{
@ObservedObject var dm: DataManager
@State private var searchTerm : String = ""
var airport : AirportModel
@Binding var dismissFlag: Bool
var body: some View {
VStack {
// fakebar
SearchBar(text: $searchTerm)
List{
ForEach(dm.airportVector.filter{
// self.searchTerm.isEmpty ? true :
$0.aptICAO.localizedCaseInsensitiveContains(searchTerm)
}, id: \.self){ item in
Text(item.aptICAO)
}
}
}
}
// bar for Airport List
var fakebar: some View {
ZStack {
HStack {
Spacer()
Image(systemName: "chevron.compact.down")
.font(.system(size: 60))
.aspectRatio(contentMode: .fit)
.foregroundColor(.white)
Spacer()
}
HStack {
Spacer()
Button(action: {
self.dismissFlag.toggle()
}) {
Text("Chiudi")
.fontWeight(.bold)
.foregroundColor(.white)
.padding(.horizontal)
}
}
}
.frame(height: 44)
.background(Color.red.padding(.top, -44))
}
}
I create my vector at the first star of the app using the below function, (using a file json)
func openfilejson (fileName : String, completition: completition) {
if let path = Bundle.main.path(forResource: fileName, ofType: "json") {
do {
let fileUrl = URL(fileURLWithPath: path)
let datafile = try Data(contentsOf: fileUrl,options: .mappedIfSafe)
let json = JSON(data:datafile)
for (key,_) in json {
let airport = AirportModel(aptICAO: "", aptName: "", aptCity: "", aptCountry: "", aptIATA: "")
airport.aptName = json[key]["name"].stringValue
airport.aptCity = json[key]["city"].stringValue
airport.aptCountry = json[key]["country"].stringValue
airport.aptIATA = json[key]["iata"].stringValue
airport.aptICAO = json[key]["icao"].stringValue
airportVector.append(airport)
}
} catch {
print("ERRORE OPEN FILE AEROPORTI")
}
}
saveAirportVector()
completition()
}
thanks for the help, look for some way to speed up the list Thanks
来源:https://stackoverflow.com/questions/59580088/swiftui-big-list-search