ios – 函数在代码完成在swift中运行之前返回

ios – 函数在代码完成在swift中运行之前返回,第1张

概述我创建了一个类函数,它包含一个闭包,它将位置坐标反向地理编码为地址字符串.我最初把它写在一个viewcontroller中,但是我需要在几个地方运行这个代码. 我的问题是类函数在闭包运行之前返回字符串,因此返回的字符串为空.有什么办法可以解决这个问题?是否有更好的方法来组织我的代码而不是使用类函数? import CoreLocationclass LocationUtil: CLLocatio 我创建了一个类函数,它包含一个闭包,它将位置坐标反向地理编码为地址字符串.我最初把它写在一个vIEwcontroller中,但是我需要在几个地方运行这个代码.

我的问题是类函数在闭包运行之前返回字符串,因此返回的字符串为空.有什么办法可以解决这个问题?是否有更好的方法来组织我的代码而不是使用类函数?

@H_301_13@import CoreLocationclass LocationUtil: CLLocation { class func getLocationAddress(location:CLLocation?) -> Nsstring { var geocoder = CLGeocoder() var addressstring : String = "" if location != nil { geocoder.reverseGeocodeLocation(location,completionHandler: {(placemarks,error)->VoID in var placemark:CLPlacemark! if error == nil && placemarks.count > 0 { placemark = placemarks[0] as CLPlacemark if placemark.subThoroughfare != nil { addressstring = placemark.subThoroughfare + " " } if placemark.thoroughfare != nil { addressstring = addressstring + placemark.thoroughfare + "," } if placemark.locality != nil { addressstring = addressstring + placemark.locality + "," } if placemark.administrativeArea != nil { addressstring = addressstring + placemark.administrativeArea + " " } if placemark.postalCode != nil { addressstring = addressstring + placemark.postalCode + " " } if placemark.country != nil { addressstring = addressstring + placemark.country } } println("Address in closure: \(addressstring)") //prints addresss }) } println("Address out of closure: \(addressstring)") // doesn't print address return addressstring //this returns nothing }}解决方法 geocoder.reverseGeocodeLocation异步运行,仅在完成后调用completionHandler.

因此,获得返回值显然不是一种选择.相反,接受闭包作为类函数的输入/参数

@H_301_13@class func getLocationAddress(location: CLLocation,getLocCompletionHandler : (addressstring : String?,error : NSError?) -> VoID) { geocoder.reverseGeocodeLocation(location,error)->VoID in //Your current code //... //... println("Address: \(addressstring)") //Instead of returning the address string,call the 'getLocCompletionHandler' getLocCompletionHandler(addressstring: addressstring,error: error) })}

当你调用这个函数时,不要使用返回值,而是等待调用闭包:

@H_301_13@LocationUtil.getLocationAddress(currentLocation,completionHandler: { (addressObject,error) -> VoID in println("Address: \(addressstring)") //OR handle the error appropriately}

阅读closures以更好地理解这个概念.

就代码组织而言,在这种情况下,类函数是一个不错的选择.

总结

以上是内存溢出为你收集整理的ios – 函数在代码完成在swift中运行之前返回全部内容,希望文章能够帮你解决ios – 函数在代码完成在swift中运行之前返回所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1006171.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-22
下一篇2022-05-22

发表评论

登录后才能评论

评论列表(0条)

    保存