[英]How do I save the results of a MKLocalSearch to an Array?
I am experiencing a bit of trouble, while working on my app in SwiftUI. I want to append relevant data, summarized in an object, to an array and return this.我在 SwiftUI 中处理我的应用程序时遇到了一些麻烦。我想将 append 中的相关数据汇总到一个数组中,并返回一个 object 中。 While returning the array, I could see by debugging, that it is empty.
在返回数组时,我可以通过调试看到它是空的。 Debugging in the for loop showed me, that location objects are created and appended, but are not being "saved" in the array.
for 循环中的调试告诉我,位置对象已创建并附加,但未“保存”在数组中。 The "mapItems" array on the other hand has lots of members.
另一方面,“mapItems”数组有很多成员。 What am I missing?
我错过了什么?
Here is the method I came up with:这是我想出的方法:
func searchForLocation(searchTerm: String) -> Array<Location>{
var locations = [Location]
let searchReqeust = MKLocalSearch.Request()
searchRequest.region = region //region is a published variable and is determined before
searchRequest.naturalLanguageQuery = searchTerm
let search = MKLocalSearch(request: searchRequest)
search.start{response, error in
//error handling
.
.
.
//empty response.mapItems handling
.
.
.
for item in response!mapItems{
let location = createLocationFromItem(item: item)
locations.append(location)
}
}
return locations
}
My locations class if following:我的位置 class 如果以下:
class Location: Identifiable{
var id= UUID()
var coordinates: CLLocationCoordinate2d
//And its proper init method
}
Your searchForLocation
has an asynchronous function inside ( search.start{...}
), and your code returns before it has finished getting the results.您的
searchForLocation
内部有一个异步 function ( search.start{...}
),并且您的代码在完成获取结果之前返回。 To "wait" for the results use a completion/closure handler, something like this:要“等待”结果,请使用完成/关闭处理程序,如下所示:
func searchForLocation(searchTerm: String, completion: @escaping ([Location]) -> ()) {
var locations = [Location]() // <-- here
// ....
search.start{response, error in // <-- here asynchronous function
//... todo deal with errors, eg return completion([])
for item in response!mapItems {
let location = createLocationFromItem(item: item)
locations.append(location)
}
completion(locations) // <- here return when finished
}
}
and call the function like this:并像这样调用 function:
searchForLocation(searchTerm: "Tokyo") { results in
print("\(results)") // <-- here results available, not before
}
I suggest you read-up on how to create and use asynchronous functions
, these are important concepts to master to code effectively in Swift.我建议您阅读如何创建和使用
asynchronous functions
,这些是在 Swift 中有效编码需要掌握的重要概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.