我创建了一个类来为我的 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
}
}
最佳答案
必须初始化当前类的所有实例变量之前初始化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/