【问题标题】:List of filter item SwiftUI筛选项列表 SwiftUI
【发布时间】:2020-01-05 07:40:33
【问题描述】:

我正在尝试列出通过带有转义闭包的函数接收到的过滤器项目的结果。 如果我在 Playground 中尝试该功能,它可以工作,所以现在我尝试在 SwiftUI 列表中使用它。

但是 Xcode 给了我警告...

无法将类型“()”的值转换为闭包结果类型“_”

这里是我的搜索功能

 typealias exit = (([AirportModel]) -> ())

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

这里是我的清单

    var body: some View {
        VStack {
            //            fakebar
            SearchBar(text: $searchTerm)

            List {
                dm.filter(valoreSearhed: searchTerm, arrayTosearh: dm.airportVector) { (item) in
                    ForEach(item) { valore in
                        Text(valore.aptICAO)
                    }
                }


            }
        }

    }

【问题讨论】:

    标签: arrays swift sorting closures swiftui


    【解决方案1】:

    您需要将所有 View 元素保留在同一个线程中,无需分派。

    因此,将您的过滤器功能更改为:

    func filter (valoreSearhed: String, arrayTosearh: [AirportModel]) -> [AirportModel]  {
        return arrayTosearh.filter { $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed) }
    }
    

    然后将您的View 代码发送到:

    List {
        ForEach(dm.filter(valoreSearhed: searchTerm, arrayTosearh: dm.airportVector)) { valore in
            Text(valore.aptICAO)
        }
    }
    

    编辑

    要在另一个线程中进行过滤,请在结果中保留一个 @State 变量:

    @State var filteredAirports: [AirportModel] = []
    
    init() {
        dm.filter( ... ) {
            self.filteredAirports = $0
        }
    }
    
    var body: some View {
        VStack {
            List {
                ForEach(filteredAirports) { valore in
                    Text(valore.aptICAO)
                }
            }
        }
    }
    

    【讨论】:

    • 明白了...问题是我需要在不同的线程中进行搜索,因为我要搜索的向量非常大
    • 所以你需要一个带有结果的@State var。然后你可以让它在结果到达时更新视图。
    • 查看以上答案的补充。
    • 我改变了删除闭包的函数,我把你的。我在 init() init() { dm.filter(valoreSearhed: searchTerm, arrayTosearh: dm.airportVector) { self.filteredAirports = $0 } } 上收到警告
    • 是的,是YourView.init()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多