Swift返回值

时间:2015-12-03 15:02:09

标签: swift return

所以我正在创建一个显示地图和当前位置的应用。现在我做了一个按钮,当我按下按钮时,它应该在我的位置上做一个标记(注释)。

所以我有这个功能抓住我当前的位置,以便我可以在地图上显示。

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

我google了很多,我搜索了堆栈溢出。但我很快就很新。似乎无法找到或理解如何解决它。

我希望有人可以帮助我并向我解释我应该如何解决这个问题!

提前致谢!

1 个答案:

答案 0 :(得分: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,因此会显示错误消息。