swift - 我不明白我的代码中的 Property 'self.heading' not initialized at super.init 调用错误

标签 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

最佳答案

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

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

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

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

关于swift - 我不明白我的代码中的 Property 'self.heading' not initialized at super.init 调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944611/

相关文章:

ios - 尝试仅在启用位置服务时运行代码导致无限循环

ios - 在 SwiftUI 中滑动列表时隐藏导航栏

iphone - 为什么 SWIFT 打印“可选(...)

ios - Swift 如何重构从 API 获取数据?

arrays - Swift:创建具有不同对象实例默认值的数组

ios - Locationmanager didchangeauthorizationstatus 未在后台调用

ios - CLLocationManagerDelegate 方法未更新

swift - 如何在 SwiftUI 中创建网格

ios - 当容器大小发生变化时,考虑到安全区域被忽略,SwiftUI TabView 会失去选择

ios - 多行导航栏标题