代码之家  ›  专栏  ›  技术社区  ›  nc14

在Swift数组中添加新位置

  •  0
  • nc14  · 技术社区  · 4 年前

    我试图将位置添加到数组中,这样我就可以计算累积距离,但我一直在思考如何将这些位置添加到我自己的数组中,它只是一直返回相同的位置。它很好地计算了距离(我用硬编码的位置进行了测试),我想我在打电话 startUpdatingLocations 由于不确定问题所在,我尝试了各种方法试图添加到数组中,但现在我得到了 No exact matches in call to instance method 'append' :

    class RaceViewController: UIViewController, CLLocationManagerDelegate {
    
    var locations : [CLLocation] = []
    var locationManager: CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if (CLLocationManager.locationServicesEnabled())
               {
                   locationManager = CLLocationManager()
                   locationManager.delegate = self
                   locationManager.desiredAccuracy = kCLLocationAccuracyBest
                   locationManager.requestAlwaysAuthorization()
               }
           }
    
    @IBAction func trackPressed(_ sender: UIButton) {
        
        locationManager.startUpdatingLocation()
        print(totalDistance(of: locations))
        print(locations)
        print(locationManager.location)
    }
    
    //get total distance between locations
    func totalDistance(of locations: [CLLocation]) -> CLLocationDistance {
        var distance: CLLocationDistance = 0.0
        var previousLocation: CLLocation?
        
    //trying here to add the location to the array of locations as and when it updates
        locations.append(contentsOf: locationManager.location)
        
        locations.forEach { location in
            if let previousLocation = previousLocation {
                distance += location.distance(from: previousLocation)
            }
            previousLocation = location
        }
        
        return distance
    }
    

    }

    1 回复  |  直到 4 年前
        1
  •  2
  •   Shehata Gamal    4 年前

    你使用 (contentsOf: 它附加的是数组而不是项目,因此替换

    locations.append(contentsOf: locationManager.location)
    

    locations.append(locationManager.location) // recommended 
    

    或者

    locations.append(contentsOf: [locationManager.location]) // not recommended