我为我的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
}
}
答案 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()
}