是否可以从我的 locationManager 函数中 return 加倍?

Is it possible to return a double from my locationManager function?

我希望能够在每个 IBAction 函数中调用 locationManager 函数。但我不知道如何处理函数调用中的所有 locationManager 参数。如何处理函数调用中的所有参数?

我试过这样做。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> Double {
    ...
    return distance
    }

但我收到警告,提示格式不正确。然后,我不知道如何调用 locationManager。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let latWork = 39.950230
    let longWork  = -75.158820
    let latHome = 40.005140
    let longHome = -75.210040

    let locationManager = CLLocationManager()

    @IBOutlet weak var distanceTraveledLabel: UILabel!

    @IBOutlet weak var distanceRemainingLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.requestWhenInUseAuthorization()

        locationManager.delegate = self
        locationManager.desiredAccuracy = 
kCLLocationAccuracyHundredMeters
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, 
didUpdateLocations locations: [CLLocation]) {
        let location = locations.last!
        let distance = location.distance(from: CLLocation(latitude: 
CLLocationDegrees(latWork), longitude: CLLocationDegrees(longWork)))
        print(distance)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func homeTapped(_ sender: Any) {
        //function that happens when home button is tapped
        print("you tapped home")
        //call locationManager function
    }

@IBAction func workTapped(_ sender: Any) {
        //function that happens when work button is tapped
        print("you tapped work")
        //call locationManager function
    }
}

你能做的是;有两个变量将纬度和经度保存为双精度(或者你也可以有一个变量作为位置):

var latitude: Double?
var longitude: Double?

然后在 didUpdateLocations 方法中每次位置变化时更新这些变量:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        latitude = location.coordinate.latitude
        longitude = location.coordinate.longitude
    }
}

然后在您的操作方法中,从这些经纬度值中获取位置信息,例如:

//you can access the current location from lat long values, and then calculate distances inside action buttons if you like.
@IBAction func homeTapped(_ sender: Any) {
    //latitude, longitude will be updated with user's current location.

}

@IBAction func workTapped(_ sender: Any) {
    //latitude, longitude will be updated with user's current location.       
}