【问题标题】:How to run this Search function in background Thread如何在后台线程中运行此搜索功能
【发布时间】:2020-04-22 19:07:00
【问题描述】:

我正在尝试使用 swiftUI 在后台线程中运行此搜索,但我不知道在哪里以及如何放置代码 DispatchQueue.global().async {}

我试图在主视图中渲染显示结果的列表,但给了我错误。我尝试将它放在运行搜索的函数中,但也会给我错误。

这里是我对搜索栏和功能的看法

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

            List{

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

            }
        }

    }

这里是我的搜索功能

  func filter (valoreSearhed: String, arrayTosearh: AirportVector) -> [AirportModel]  {
        // if I use like this Xcode give me warning Cannot convert return expression of type '()' // to return type '[AirportModel]'

        DispatchQueue.global().async {  
               arrayTosearh.filter {
            //        valoreSearhed.isEmpty ? true :
                            $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed)
                        }
        }



    }

如果我删除调度队列,搜索会完美运行,但它会在几秒钟内挡住我的视线。

谢谢

【问题讨论】:

    标签: swift xcode multithreading list swiftui


    【解决方案1】:

    如果您使用后台线程或 DispatchQueue 执行搜索功能,则不能期望该函数返回 [AirportModel],因为该函数将继续运行,并且在完成搜索之前return

    这就是为什么 XCode 告诉你它不能返回 (),它不能以线性方式检测返回类型。

    我建议使用闭包来获取所需的详细信息。这是您可以执行的操作的 sn-p:

    func filter (valoreSearhed: String, arrayTosearh: AirportVector, completionBlock: (airports: [AirportModel]) -> Void)  {
        DispatchQueue.global().async {  
            let results  = arrayTosearh.filter { $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed) }
            completionBlock(results)
        }
    }
    

    示例用法:

     var body: some View {
        VStack {
            //            fakebar
            SearchBar(text: $searchTerm)
            List {
                dm.filter(valoreSearhed: searchTerm, arrayTosearh: dm.airportVector) { airports in 
                    ForEach(airports) { airport in
                        Text(airport.aptICAO)
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 我尝试了你的函数,但收到很多警告,例如,一行上的连续声明必须用';'分隔或函数声明体中应有“{”,函数类型不能有参数标签;在“机场”之前使用“_”
    • 我在这篇文章中添加了我写的代码,但 Xcode 一直给我警告 [stackoverflow.com/questions/59596993/…Cannot convert return expression of type '()' to return type '[AirportModel]'
    • 您需要删除 `-> [AirportModel] 因为它不再以线性方式返回它。我已经编辑了函数以反映它应该是正确的函数
    • 仍然,给出错误...无法将类型 '()' 的值转换为闭包结果类型 '_'
    猜你喜欢
    • 1970-01-01
    • 2017-08-26
    • 2014-09-27
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2021-01-20
    相关资源
    最近更新 更多