【问题标题】:Return CLLocationCoordinate2D to struct将 CLLocationCoordinate2D 返回到结构
【发布时间】:2018-05-30 19:30:29
【问题描述】:

我是编程新手,我的问题是如何将变量类型 CLLocationCoordinate2D 的数据返回到坐标,即结构的类型。正在尝试开发天气应用程序。

我有一个结构:

struct Coordinates {
    let latitude: Double
    let longitude: Double
}

我的代码如下:

//getting coordinates from String
func getCoordinateFrom(address: String, completion: @escaping(_ coordinate: CLLocationCoordinate2D?, _ error: Error?) -> () ) {
                CLGeocoder().geocodeAddressString(address) { placemarks, error in
                    completion(placemarks?.first?.location?.coordinate, error)
                }
            }

//When the User type his city, coordinates have type of CLLocationCoordinate2D    
@IBAction func changeCityButtonPressed(_ sender: UIButton) {
            guard let address = textField.text else { return }
            getCoordinateFrom(address: address) { coordinate, error in
                guard let coordinate = coordinate, error == nil else { return }
                DispatchQueue.main.async {
                    print(coordinate)
                }  
            }
        }

我有一个常数,我的任务是将坐标从函数转移到这个常数。

  let coordinates = Coordinates(latitude: 00.617366, longitude: 37.617366)

问题是函数中的这些坐标是闭包的。所以我不能退回它们等等。我试图找到正确的答案,但没有结果。有人有一些建议/解决方案吗?

【问题讨论】:

  • 你想从哪里返回坐标
  • 来自位于 func changeCityButtonPressed 中的“让坐标”。它有城市的纬度和经度
  • 你想要存储坐标的变量在哪里
  • @Over 请完美解释没有人能理解你的问题

标签: ios swift coordinates clgeocoder cllocationcoordinate2d


【解决方案1】:

在这一行:

 let coordinates = Coordinates(latitude: 00.617366, longitude: 37.617366)

let 替换为var

在这段代码中:

  @IBAction func changeCityButtonPressed(_ sender: UIButton) {
        guard let address = textField.text else { return }
        getCoordinateFrom(address: address) { coordinate, error in
            guard let coordinate = coordinate, error == nil else { return }
            DispatchQueue.main.async {
                print(coordinate)
            }  
        }
    }

替换这个:

  guard let coordinate = coordinate, error == nil else { return }
            DispatchQueue.main.async {
                print(coordinate)
            } 

通过这个:

  guard let coordinate = coordinate, error == nil else { return }
            coordinates.latitude = coordinate.latitude
            coordinates.longitude = coordinate.longitude
            DispatchQueue.main.async {
                print(coordinate)
            } 

这就是你的坐标变量将如何更新为新的纬度

【讨论】:

  • 它有助于解决您的问题?
  • 几乎。谢谢你!你的代码 + ".self" 对我有帮助:guard let coordinate = coordinate, error == nil else { return } self.coordinates.latitude = coordinate.latitude self.coordinates.longitude = coordinate.longitude
  • 哦哈哈哈哈我忘了self
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-25
  • 2015-05-09
相关资源
最近更新 更多