我对完成处理程序有很大的困难。而且我不知道如何使用这个。
以下是带有完成处理程序的函数,用于根据字符串地址获取地理坐标。
func getLocation(from address: String, completion: @escaping (_ location: CLLocation?)-> Void) {
guard let address = address as? String else { return }
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,
let location = placemarks.first?.location else {
completion(nil)
return
}
completion(location)
}
}
我是这样调用这个函数的
getLocation(from: address) { location in
print("Location is", location.debugDescription)
if case self.currentLocation = location {
self.queryGenerator(searched: self.searchController.isActive, queryString: "")
} else {
self.showAlert(alertTitle: "No businsesses nearby", message: "Try going back and changing the address")
}
}
我一直得到一个nil currentLocation
. 如果有人能把这个问题给我说清楚,那就太好了。
在获取位置后,我进行了一个网络调用,它向我发送了一个包含业务坐标和服务半径的自定义对象。如果服务半径小于或等于业务坐标和currentLocation之间的距离,那么我将其添加到一个数组中,该数组将填充一个UITableView。这里是我进行上述计算的函数。
func applicableRestaurants(allQueriedRestaurants: [Restaurant]) -> [Restaurant] {
var filteredRestaurants = [Restaurant]()
for thisRestaurant in allQueriedRestaurants {
let restaurantCoordinate = CLLocation(latitude: thisRestaurant.geoPoint.latitude, longitude: thisRestaurant.geoPoint.longitude)
if restaurantCoordinate.distance(from: self.currentLocation!) <= thisRestaurant.distance {
filteredRestaurants.append(thisRestaurant)
}
}
return filteredRestaurants
}
我的猜测(这只是猜测)是你在没有理解其含义的情况下使用了这个表达式。
if case self.currentLocation = location {
self.queryGenerator...
I 认为 你的意思可能是:
if let location = location {
self.currentLocation = location
self.queryGenerator...
我想你可能认为这些都是等同的,但它们不是。