【问题标题】:why in this code would I be getting "Unexpected non-void return value in void function"为什么在这段代码中我会得到“无效函数中的意外非无效返回值”
【发布时间】:2016-02-19 00:16:52
【问题描述】:

下面是代码:

private func getReverseGeocodeData(newCoordinates : CLLocationCoordinate2D) -> CLPlacemark? {
  let clLocation = CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude)
  GCAnnotation.geocoder.reverseGeocodeLocation(clLocation) { placemarks, error in
    if let pms = placemarks {
      let pm : CLPlacemark? = pms.first as CLPlacemark?
      return pm // ==> "Unexpected non-void return value in void function"
    }
  }
  return nil
}

【问题讨论】:

  • 即我已将 pm 作为可选项并返回它......所以这不应该工作吗?
  • 包含return pm的闭包没有指定返回值,只有外部函数有。

标签: ios xcode swift optional optional-parameters


【解决方案1】:

您需要在函数中添加一个回调参数,您可以在 reverseGeocodeLocation 完成后调用该参数并将 pm 作为参数传递。

private func getReverseGeocodeData(callback : (CLPlaceMark?)-> Void, newCoordinates : CLLocationCoordinate2D) -> CLPlacemark? {
  let clLocation = CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude)
  GCAnnotation.geocoder.reverseGeocodeLocation(clLocation) { placemarks, error in
    if let pms = placemarks {
      let pm : CLPlacemark? = pms.first as CLPlacemark?
       callback(pm)
    }
  }
  return nil
}

【讨论】:

    【解决方案2】:

    GCAnnotation.geocoder.reverseGeocodeLocation(clLocation) 在它自己的闭包和函数中。当你使用这样的回调时,你不能返回这样的值。但是,如果您确定该函数立即返回一个值,您可以执行以下操作:

    private func getReverseGeocodeData(newCoordinates : CLLocationCoordinate2D) -> CLPlacemark? {
        let pm: CLPlacemark?
        let clLocation = CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude)
        GCAnnotation.geocoder.reverseGeocodeLocation(clLocation) { placemarks, error in
            if let pms = placemarks {
                 pm = pms.first as CLPlacemark?
            }
        }
        return pm
    }
    

    【讨论】:

    • 那不行,它总是会在调用完成处理程序之前返回,并且每次都返回nil
    • ok - 所以这意味着如果您需要在几个地方调用 reverseGeocodeLocation 函数,您不妨直接在每个地方调用它,而不是尝试将其放入其中像我一样拥有自己的功能。因为无论如何您都必须在回叫中真正执行您想做的事情。有意义吗?
    • 是的,当然,您也可以在函数中请求回调作为参数并将数据传回。
    猜你喜欢
    • 2021-02-16
    • 2010-09-17
    • 2014-07-14
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多