不能在属性初始值设定项中使用实例成员'service';属性初始值设定项在 'self'可用之前运行



我试图从structgService中获取经度和纬度,并将其设置在Map上。但是由于错误"而无法初始化@State var region;无法在属性初始值设定项中使用实例成员"service";属性初始值设定项在"self"可用之前运行;关于service.latitudeservice.longitude

struct DetailCardView: View {
let service: gService
@State var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
var body: some View {
Map(coordinateRegion: $region, annotationItems: [MapPoint(coordinates: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude))]) { location in
MapAnnotation(coordinate: location.coordinates) {
Circle()
.stroke(.red, lineWidth: 3)
.frame(width: 50, height: 50, alignment: .center)
}
}

我在谷歌上搜索了这个问题,但有不同的情况。

基本上,编译器所说的是"我还在创建你的DetailCardView的实例,我还不知道service的值是多少,所以我不能在region中使用它;。

解决方案是将service传递给一个常数,该常数将用于初始化两个属性。您需要为您的视图创建一个初始值设定项,在其中传递此常量。

它看起来是这样的:

let service: gService

// Rather than service.longitude and service.latitude, use a dummy value, like 0.0
// Recommended this var to be private
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
// Here's your initializer
init(service: gService) {
self.service = service      // Use service to initialise self.service
// Use service - and NOT self.service - to initialise region
region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
}
var body: some View {
...    // The rest of your code

您可以尝试的另一种方法是在视图出现时删除init()并设置region,如下所示:

let service: gService

// Rather than service.longitude and service.latitude, use a dummy value, like 0.0
// Recommended this var to be private
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
var body: some View {
Map(coordinateRegion: $region, annotationItems: [MapPoint(coordinates: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude))]) { location in
MapAnnotation(coordinate: location.coordinates) {
Circle()
.stroke(.red, lineWidth: 3)
.frame(width: 50, height: 50, alignment: .center)
}
.onAppear {
region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
}
}