2015-12-03 32 views
0

因此,我正在製作一個顯示地圖和當前位置的應用程序。現在我做了一個按鈕,當我按下按鈕時,它應該在我的位置上做一個標記(註釋)。Swift返回值

所以我有這個函數抓住我的當前位置,以便我可以在地圖上顯示它。

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

    let location = locations.last 

    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) 

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) 

    self.mapView.setRegion(region, animated: true) 

    self.locationManager.stopUpdatingLocation() 

    return center 
} 

現在我想在另一個函數中使用變量「Center」的數據。但是當我「返回中心」時。我得到以下錯誤:「Unexpected non-void return value in void function

我搜索了很多,我搜索了堆棧溢出。但我很快就有了新的發現。似乎無法找到或理解如何解決它。

我希望有人能幫助我,向我解釋我該如何解決這個問題!

提前致謝!

回答

1

既然你想返回center這是一個CLLocationCoordinate2D,你的函數的簽名必須明確地返回一個CLLocationCoordinate2D,像這樣的:在簽名

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> CLLocationCoordinate2D { 

    let location = locations.last 

    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) 

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) 

    self.mapView.setRegion(region, animated: true) 

    self.locationManager.stopUpdatingLocation() 

    return center 
} 

沒有-> CLLocationCoordinate2D,假設該函數返回void,因此你得到的錯誤信息。