Массив фильтров SwiftUI через searchBar - PullRequest
0 голосов
/ 05 января 2020

Мне предложили выполнить поиск по массиву в другом потоке (чтобы избежать блока моего обзора) использования переменной @state, но я продолжаю получать эту ошибку.

Аргумент передан вызов, который не требует аргументов ...

Я упростил свой код в новом проекте и все еще дал мне ошибку .. ищет несколько советов ..

это мой contentView

import SwiftUI

struct ContentView: View {
    @ObservedObject var dm: DataManager
    @State private var searchTerm : String = ""
    @State var filteredAirports: [AirportModel] = []


    init() {
           dm.filter(valoreSearhed: searchTerm, arrayTosearh: dm.airportVector) {
               self.filteredAirports = $0
           }
       }

    var body: some View {
        VStack {
             SearchBar(text: $searchTerm)
            List{
                ForEach(filteredAirports){ item in
                    Text(item.aptICAO)
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(dm: DataManager())  // Argument passed to call that takes no arguments
    }
}

Я попытался удалить предварительный просмотр, но он дал больше ослабления .. возможно, что init должен находиться в другом месте?

здесь ниже функции в моем классе DataManager для фильтра

 func filter (valoreSearhed: String, arrayTosearh: [AirportModel],  closure: @escaping exit)  {
        DispatchQueue.global().async {
            let aeroportoFiltrato  = arrayTosearh.filter { $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed) }
            closure(aeroportoFiltrato)
        }
    }

Я положил сюда свой класс DataManager на всякий случай ... но я думаю, что проблема не здесь ..

class DataManager: ObservableObject {
    let objectWillChange = PassthroughSubject<Void,Never>()
    static let shared = DataManager()

    @Published var airportVector : [AirportModel] = []{
    didSet {
        objectWillChange.send()
    }}

    typealias AirportVector = [AirportModel]
    typealias completition = () -> ()
    typealias exit = ((_ airport: [AirportModel]) -> ())
    init() {

        debugPrint("APRO")
        self.caricaDati()

        self.openfilejson(fileName: "apt") {
            debugPrint("FINISH LOAD")
        }

        self.caricaDati()



    }
    var filePath : String = ""

    func caricaDati() {
        // creiamo il percorso al file
        filePath = cartellaDocuments() + "/airport.plist"

        // usiamo NSFileManager per sapere se esiste un file a quel percorso
        if FileManager.default.fileExists(atPath: filePath) {

            // se c'è de-archiviamo il file di testo nell'array
            // serve il blocco do try catch
            do {
                // proviamo a caricare il file dal percorso creato in precedenza
                let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
                // creiamo il decoder
                let decoder = PropertyListDecoder()
                // proviamo a decodificare il file nell'array
                airportVector = try decoder.decode(AirportVector.self, from: data)
            } catch {
                // se non ce la fa scriviamo in console l'errore
                debugPrint(error.localizedDescription)
            }

            // adesso abbiamo i dati e possiamo far andare l'App

            // *** ATTENZIONE***
            // funziona solo se il Model è conforme a Codable
            // *** ********* ***
        }
    }

    func salva() {
        // creiamo l'encoder
        let encoder = PropertyListEncoder()
        encoder.outputFormat = .xml // impostiamo l'output corretto
        // serve il blocco do try catch
        do {
            // proviamo a codificare l'array
            let data = try encoder.encode(airportVector)
            // proviamo a salvare l'array codificato nel file
            try data.write(to: URL(fileURLWithPath: filePath))
        } catch {
            // se non ce la fa scriviamo in console l'errore
            debugPrint(error.localizedDescription)
        }

        // *** ATTENZIONE***
        // funziona solo se il Model è conforme a Codable
        // *** ********* ***
    }

    func cartellaDocuments() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        //print(paths[0])
        return paths[0]
    }

    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: "")

                      airport.aptICAO = json[key]["icao"].stringValue

                      airportVector.append(airport)
                    debugPrint(airport.aptICAO)
                  }

              } catch {
                   print("ERRORE OPEN FILE AEROPORTI")
              }

          }
           salva()
          completition()
      }


    func filter (valoreSearhed: String, arrayTosearh: [AirportModel],  closure: @escaping exit)  {
        DispatchQueue.global().async {
            let aeroportoFiltrato  = arrayTosearh.filter { $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed) }
            closure(aeroportoFiltrato)
        }
    }
}

и моя модель

import Foundation

class AirportModel: Identifiable , Codable {
    var id : UUID = UUID()
    var aptICAO : String

init(aptICAO: String) {
    self.aptICAO = aptICAO
}
}

заранее спасибо за помогите .. честно говоря, я не могу понять, почему это предупреждение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...