【问题标题】:Coordinates not stored in Array when inserted插入时坐标未存储在数组中
【发布时间】:2017-06-14 01:54:51
【问题描述】:

我正在尝试将坐标存储在数组中。代码运行良好,但是每次迭代新实现的坐标后,数组计数仍然保持不变?

let manager = CLLocationManager()

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]
    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01,0.01) //shows the size of map screen
    let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
    let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
    map.setRegion(region, animated: true)
    self.map.showsUserLocation = true
    let LAT = Double(location.coordinate.latitude)
    let LONG = Double(location.coordinate.longitude)
    var locationArray = [Double]()
    locationArray.insert(contentsOf: [LAT, LONG], at: 0)
    print(locationArray.count)

【问题讨论】:

    标签: arrays swift insert coordinates


    【解决方案1】:

    这种情况正在发生,因为您在每次迭代中都创建了一个新的 locationArray。您需要在更新范围之外声明 locationArray,您将在其中插入坐标。

    var locationArray = [Double]()
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[0]
        let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01,0.01) //shows the size of map screen
        let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
        let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
        map.setRegion(region, animated: true)
        self.map.showsUserLocation = true
        let LAT = Double(location.coordinate.latitude)
        let LONG = Double(location.coordinate.longitude)
        locationArray.insert(contentsOf: [LAT, LONG], at: 0)
        print(locationArray.count)
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2020-10-05
      • 1970-01-01
      相关资源
      最近更新 更多