"Value of type '(CLLocationManager, [CLLocation]) -> ()' has no member 'delegate' " swift 映射错误

"Value of type '(CLLocationManager, [CLLocation]) -> ()' has no member 'delegate' " Error in swift with mapping

在尝试查找用户位置时,我使用 CLLocationManager。我在哪里有这条线:

locationManager.delegate = self

它returns这个错误:

Value of type '(CLLocationManager, [CLLocation]) -> ()' has no member ‘delegate'

代码如下:

import CoreLocation
import UIKit
import SwiftUI
import Mapbox

class MapsViewController: UIViewController, MGLMapViewDelegate {
    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled(){
            locationManager.delegate = self //this is where I get the error said above
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
}

我试过Whosebug上的错误并自己解决了,但到目前为止没有任何帮助。 Swift & Xcode 的新版本可能有问题(因为我正在学习 this 教程)

我在 Info.plist 中添加了 Privacy - Location When In Use Usage DescriptionPrivacy - Location Always and When In Use Usage Description 以供任何想知道的人使用。

添加CLLocationManagerDelegate

class MapsViewController: UIViewController,MGLMapViewDelegate,CLLocationManagerDelegate{

是正确的,但我可能建议将对 CLLocationManagerDelegate 协议的一致性拉到它自己的扩展中:

extension MapsViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
        guard let coordinate = locations.last?.coordinate else { return }

        print("locations = \(coordinate.latitude) \(coordinate.longitude)")
    }
}

将协议一致性与基础 class 实现分开可以使代码井井有条并支持代码折叠(例如 command+option +)。这么小的view controller没关系,但是随着这个view controller的代码越来越多,使用扩展来组织它真的很方便。

请参阅 Swift 编程语言中的 Adding Protocol Conformance with an Extension