如果语句没有改变全局变量 swift

If statement is not changing global variable swift

我正在尝试设置一个函数来获取我在应用程序委托中的当前位置但是当我 print(city) 在底部时它 returns 全局变量中的原始初始化值是 "hello",即使我更新了 CLGeocoder 下的值。

AppDelegate:

    import UIKit
    import CoreData
    import CoreLocation

    let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

    var country = "hello"
    var city = "hello"

 func setupLocationManager(){
        let locationManager = CLLocationManager()
        locationManager.requestAlwaysAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }

    // Below method will provide you current location.
    func getLocation() -> [String]{
        let manager = CLLocationManager()
        manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()

        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()

        let selflocation = manager.location

        let latitude: Double = selflocation!.coordinate.latitude
        let longitude: Double = selflocation!.coordinate.longitude


        print("current latitude :: \(latitude)")
        print("current longitude :: \(longitude)")

        let location = CLLocation(latitude: latitude, longitude: longitude) //changed!!!            

        CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
            print(location)

            if error != nil {
                print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
            }

            let pm = placemarks![0]
            let speed = (selflocation?.speed)!
            city = pm.addressDictionary!["City"]! as! String
            country = pm.addressDictionary!["Country"]! as! String

            if (placemarks?.count)! > 0 {
            }
            else {
                print("Problem with the data received from geocoder")
            }
        })

        print(city)
        return [city as! String, country as! String]
    }

reverseGeocodeLocation 异步工作,因此 print 语句实际上在它完成之前发生。如果您有任何依赖于结果的逻辑,您可能需要将其放入完成处理程序闭包中。

这是因为地理编码是异步完成的,所以 print(city) 在地理编码完成之前正在执行。所以我建议你这样做。

func getLocation(completion: @escaping (Array<String>)->()){

    let manager = CLLocationManager()

    manager.desiredAccuracy = kCLLocationAccuracyBest

    manager.requestAlwaysAuthorization()

    manager.startUpdatingLocation()

    let selflocation = manager.location

    let latitude: Double = selflocation!.coordinate.latitude

    let longitude: Double = selflocation!.coordinate.longitude

    let location = CLLocation(latitude: latitude, longitude: longitude)

    CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in

        if let error = error {

            print(error.localizedDescription)

            return
        }

        if let placemark = placemarks?.first {

            if let country = placemark.country, let city = placemark.locality {

                completion([city, country])

                return

            } else {

                print("country or city was nil.")
            }
        } else {

            print("Problem with the data received from geocoder")
        }
    })
}

所以不要调用 getLocation() 而是调用

getLocation { (location) in

    print(location)
}

就像其他答案所说的那样,reverseGeocodeLocation 异步工作,因此您可能希望将 print(city) 移动到闭包内,例如 after

else {
    print("Problem with the data received from geocoder")
}

这里的问题是您在为它分配新的位置值之前获取该值。您必须稍等片刻才能获得更新后的值。