【发布时间】:2020-06-24 05:07:43
【问题描述】:
以下是我用来为每辆卡车创建位置的结构。
卡车
struct Truck {
var name: String
var imageOfTruck: String
var cuisineType: String
var customerRatings: [Int]
var customerRatingAve: Int
var menu: [MenuItem]
var currentLocation: Location
}
位置
struct Location {
var location: String
var coordinates: CLLocationCoordinate2D {
let geoCoder = CLGeocoder()
var tempCoordinates = CLLocationCoordinate2D(latitude: 0, longitude: 0)
geoCoder.geocodeAddressString(location) { (placemarks, error) in
guard
let placemarks = placemarks,
let location = placemarks.first?.location
else {
print("location not found!")
return
}
// Use your location
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
print("latitude: \(latitude)")
print("longitude: \(longitude)")
tempCoordinates.latitude = latitude
tempCoordinates.longitude = longitude
}
return tempCoordinates
}
var departureTime: String
var nextLocation: NextLocation
}
let truckOne = Truck(name: "truck one",
imageOfTruck: "image of truck one",
cuisineType: "mexican",
customerRatings: [4,4,4],
customerRatingAve: 4,
menu: [MenuItem(itemName: "taco",
itemDescription: "spicy tacos",
itemPhotos: ["image one", "image two"],
customerRatings: [4,4,4],
customerRatingAvg: 4)],
currentLocation: Location(location: "physical address goes here (removed for stack overflow)",
departureTime: "5PM",
nextLocation: NextLocation(location: "321 address street",
arrivalTime: Date(),
departureTime: Date())))
let truckTwo = Truck(name: "truck two",
imageOfTruck: "image of truck two",
cuisineType: "pizza",
customerRatings: [4,4,4],
customerRatingAve: 4,
menu: [MenuItem(itemName: "pepperoni pizza",
itemDescription: "delicious pepperoni",
itemPhotos: ["image one", "image two"],
customerRatings: [4,4,4],
customerRatingAvg: 4)],
currentLocation: Location(location: "physical address goes here (removed for stack overflow)",
departureTime: "4PM",
nextLocation: NextLocation(location: "333 cool st",
arrivalTime: Date(),
departureTime: Date())))
let arrayOfTrucks = [truckOne, truckTwo]
下面是我需要将纬度和经度拉入的函数。
func convertAddressToCoordinates() {
for trucks in arrayOfTrucks {
print("truck name: \(trucks.name) truck coordinates: \(trucks.currentLocation.coordinates)")
}
}
函数打印
卡车名称:卡车一卡车坐标:CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
卡车名称:卡车两卡车坐标:CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
但是,在计算机属性coordinates 中,经纬度设置正确。从coordinates 变量中的打印语句中,打印出以下内容
纬度:30.2968677
经度:-81.6114142
纬度:30.1535125
经度:-81.6429059
计算属性是否在实际获得latitude 和longitude 之前返回tempCoordinates?如果是这样,有什么解决方法?
【问题讨论】:
-
geocodeAddressString异步运行,这意味着稍后会调用闭包。所以它不适用于计算属性。您可能希望使用自己的完成处理程序闭包编写一个函数。