gpt4 book ai didi

arrays - 数组的平均速度和最高速度 "CoreLocation"

转载 作者:可可西里 更新时间:2023-11-01 02:01:35 25 4
gpt4 key购买 nike

我正在尝试显示用户的平均速度,而且我还想显示数组的最大值。

我搜索了论坛并找到了很多方法来实现这一点,但没有任何效果。

我试过的是//最高速度//平均速度

这是我的代码:

// Location
let manager = CLLocationManager()

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span = MKCoordinateSpanMake(0.015, 0.015)
let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)

let region = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true

// Altitude
let altitude = location.altitude
let altitudeNoDecimals = Int(altitude)

altitudeLabel.text = "\(altitudeNoDecimals)"

// m/s to km/h
let kmt = location.speed * (18/5)
let kmtLabel = Int(kmt)
statusLabel.text = "\(kmtLabel)"

// Top Speed
// let maxSpeed: Int = (kmtLabel as AnyObject).value(forKeyPath: "@maxSpeed.self") as! Int
// topSpeedLabel.text = "\(maxSpeed)"

let max = location.toIntMax()
topSpeedLabel.text = "\(max)"

// Average speed
var avg: Double = (list as AnyObject).valueForKeyPath("@avg.self") as Double
averageSpeed.text = "\(avg)"
}

override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}

最佳答案

你只需要自己将所有速度更新保存到一个数组中,它应该被定义为一个类实例属性,你可以将平均速度和最高速度定义为计算属性,这样你就不需要每次都手动更新它们您会收到位置更新。

let manager = CLLocationManager()
var speeds = [CLLocationSpeed]()
var avgSpeed: CLLocationSpeed {
return speeds.reduce(0,+)/Double(speeds.count) //the reduce returns the sum of the array, then dividing it by the count gives its average
}
var topSpeed: CLLocationSpeed {
return speeds.max() ?? 0 //return 0 if the array is empty
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
...

speeds.append(contentsOf: locations.map{$0.speed}) //append all new speed updates to the array

// m/s to km/h
let kmt = location.speed * (18/5)
let kmtLabel = Int(kmt)
statusLabel.text = "\(kmtLabel)"

// Top Speed
topSpeedLabel.text = "\(topSpeed)"

// Average speed
averageSpeed.text = "\(avgSpeed)"
}

请记住,我没有将 avgSpeedtopSpeed 的单位更改为 km/h,如果您需要,您可以在编写之前完成将它们添加到标签中,或者更确切地说,是在将它们附加到数组之前。

关于arrays - 数组的平均速度和最高速度 "CoreLocation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45870783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com