我有下面的代码,它正在工作。
if passedValue == "location1" {
var initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
centerMapOnLocation(initialLocation)
loadInitialData()
}
if passedValue == "location2" {
var initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
centerMapOnLocation(initialLocation)
loadInitialData()
}
但为了更简洁,我写了这个,但我得到了以下错误消息:“使用未解析的标识符‘初始位置’”。知道吗?
if passedValue == "location1" {
var initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
}
if passedValue == "location2" {
var initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
}
centerMapOnLocation(initialLocation)
loadInitialData()
最佳答案
声明var initialLocation: CLLocation!
外部并使用initialLocation
内部。
您可能还想在使用initialLocation
之前检查centerMapOnLocation()
是否为nil,以防万一。
if initialLocation != nil {
centerMapOnLocation(initialLocation)
}
说明:
centerMapOnLocation()
无法看到initialLocation
,因为它只存在于if
语句的内部。完整代码:
var initialLocation: CLLocation!
if passedValue == "location1" {
initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
}
else if passedValue == "location2" {
initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
}
if initialLocation != nil {
centerMapOnLocation(initialLocation)
loadInitialData()
}