我不理解在我的代码中未在super.init调用错误中初始化的属性'self.heading'

时间:2019-09-15 13:35:05

标签: swift cllocationmanager swiftui

我为我的SwiftUI应用创建了一个类,以使用CLLocationManagerDelegate获取当前标题,但是出现了Property 'self.heading' not initialized at super.init call错误。我不知道为什么我认为我不需要指定参数,因为我的课程在调用期间不接受任何参数吗?

我的LocationManager类:

class LocationManager: NSObject, CLLocationManagerDelegate, ObservableObject {

  var locationManager: CLLocationManager?
  var objectWillChange = PassthroughSubject<Void, Never>()

  @Published var heading: Double {
    willSet {
      objectWillChange.send()
    }
  }

  override init() {
    super.init()

    locationManager = CLLocationManager()
    locationManager!.delegate = self
    locationManager!.desiredAccuracy = kCLLocationAccuracyBest
    locationManager!.requestWhenInUseAuthorization()
  }

  func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    self.heading = newHeading.trueHeading.degreesToRadians
  }

}

Screen of error

1 个答案:

答案 0 :(得分:2)

必须在初始化 super 之前,先初始化当前类的所有实例变量。

因此在调用heading之前,请向super.init()添加一些初始值,例如:

override init() {
    heading = 0 // Or anything you need
    super.init()

    locationManager = CLLocationManager()
    locationManager!.delegate = self
    locationManager!.desiredAccuracy = kCLLocationAccuracyBest
    locationManager!.requestWhenInUseAuthorization()
}