在swift中为闭包内的变量添加值

时间:2017-12-24 11:39:57

标签: swift closures

我是快速语言的新手,我遇到了无法解决的问题。

运行我的应用程序后,我得到空字符串的输出: nil

所以,我的问题是如何为变量里面的变量增加值

因为当我在闭包中添加线 print(self.latLong) 时,我得到坐标的输出,但我需要在变量内部的值,因为我需要操作该变量稍后在我的代码中,我不想在该闭包内写入所有功能

这是我的代码:

import UIKit
import CoreLocation
import Firebase

var latLong: String!

override func viewDidLoad() {
    super.viewDidLoad()

    findCordiante(adress: "Cupertino, California, U.S.")
    print(latLong)
}

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 = ""
        }
    }

}

2 个答案:

答案 0 :(得分:1)

latLong为nil,因为在设置print(latLong)的值之前,在加载视图后立即调用latLong。您可以定义一个函数来处理latLong并在闭包中调用它。

import UIKit
import CoreLocation
import Firebase

var latLong: String!

override func viewDidLoad() {
    super.viewDidLoad()

    findCordiante(adress: "Cupertino, California, U.S.")
    print(latLong)
}

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!)
            //Do something with latLong now 
            self.doSomething(withlatLong: self.latLong)

        }else{
            //handle no adress
            self.latLong = ""
        }
    }

}

private func doSomething(withlatLong latLong:String) {
    //Do whatever you want with latLong 
    print(latLong)
}

答案 1 :(得分:1)

问题是geocodeAddressString以异步方式运行(即它需要很长时间才能将其写入以立即返回并在请求完成时稍后调用其闭包),因此viewDidLoad正在打印{{ 1}}在此属性最终在latLong完成处理程序闭包中设置之前。

解决方案是在您自己的代码中采用异步编程模式。例如,使用您自己的完成处理程序模式:

geocodeAddressString
相关问题