向数组添加新位置 Swift

Add new locations to an array Swift

我正在尝试将位置添加到数组中,以便我可以计算累积距离,但我仍然不知道如何将这些位置实际添加到我自己的数组中,它只是一直返回相同的位置。它可以很好地计算距离(我已经使用硬编码位置进行了测试)并且我认为我正在正确调用 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
}

}

您使用 (contentsOf: 追加 array 而不是 item ,所以 Replace

locations.append(contentsOf: locationManager.location)

locations.append(locationManager.location) // recommended 

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