我是 swift 的新手,我不知道如何处理闭包和闭包概念。
我最近问了question我发现我的变量为 nil,因为 geocodeAddressString
异步运行,所以应用打印 latLong
远早于此属性最终设置。
但这是我无法理解的新问题:
import UIKit
import CoreLocation
import Firebase
var latLong: String!
override func viewDidLoad() {
super.viewDidLoad()
}
func findCordiante(adress:String){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(adress) {
placemarks, error in
if (placemarks != nil){
let placemark = placemarks?.first
let lat = placemark?.location?.coordinate.latitude
let lon = placemark?.location?.coordinate.longitude
self.latLong = String(describing: lat!) + "," + String(describing: lon!)
}else{
//handle no adress
self.latLong = ""
}
}
}
@IBAction func createSchool(_ sender: Any) {
//when user press button i want execute function and assign value to variable latLong
findCordiante(adress: "Cupertino, California, U.S.")
//so then I need to manipulate with that value here, let's say example
//example
print("Hi user, your coordinates is \(latLong)")
}
当我在闭包内添加 print(latLong)
时,它正在打印,但我不想在闭包内执行所有功能。
只是我想将func findCordiante()
的结果添加到变量latLong
,这样之后我就可以在内部的任何地方使用该变量进行操作类
最佳答案
要了解的主要事情是将地址解析为坐标(以及许多其他地理定位操作)需要时间,因此返回结果会有相当长的延迟。在延迟期间,应用程序会继续运行并且应该响应用户操作。
这就是为什么要使用闭包的原因,即将操作分成两部分:
- 开始操作(您的
findCoordinate
函数) - 操作完成后完成 Action (闭包,用作回调)
在这两个部分之间,您的应用程序运行正常。它不会等待或阻塞。如果你想要一个等待行为,你必须自己实现它(例如禁用按钮,忽略用户手势等(。
您可以轻松地将闭包中的部分代码移动到一个单独的函数中:
func findCordiante(adress:String){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(adress) {
placemarks, error in
if let placemarks = placemarks {
self.findCoordinateCompleted(placemarks)
} else {
self.findCoordinateFailed()
}
}
}
func findCoordinateCompleted(placemarks: [CLPlacemark]) {
let placemark = placemarks.first!
let lat = placemark.location!.coordinate.latitude
let lon = placemark.location!.coordinate.longitude
latLong = String(describing: lat) + "," + String(describing: lon)
completeCreatingSchool()
}
func findCoordinateFailed() {
latLong = ""
print("Hi user, invalid address")
// do more stuff here
}
@IBAction func createSchool(_ sender: Any) {
findCoordinate(adress: "Cupertino, California, U.S.")
}
func completeCreatingSchool() {
//example
print("Hi user, your coordinates is \(latLong)")
}
关于swift - swift 中的闭包操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47970217/