求和Zstack中某个函数的错误,但该函数没有错误



我创建了函数getAnnotations,在视图内部调用该函数时,甚至在定义函数时,都没有错误,但Map得到2个错误:

初始化程序"init(coordinateRegion:interactionModes:showsUserLocation:userTrackingMode:annotationItems:annotationsContent:("要求"MKPointAnnotation.Type.Element"符合"Identifiable">

类型"MKPointAnnotation.Type"不能符合"RandomAccessCollection">

函数getAnnotations:的代码

func getAnnotations(completion: @escaping (_ annotations: [MKPointAnnotation]?) -> Void) {
let db = Firestore.firestore()

db.collection("annotations").addSnapshotListener { (querySnapshot, err) in
guard let snapshot = querySnapshot else {
if let err = err {
print(err)
}
completion(nil) // return nil if error
return
}
guard !snapshot.isEmpty else {
completion([]) // return empty if no documents
return
}

var annotations = [MKPointAnnotation]()

for doc in snapshot.documents {
if let lat = doc.get("lat") as? String,
let lon = doc.get("long") as? String,
let latitude =  Double(lat),
let longitude = Double(lon) {
let coord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let annotation = MKPointAnnotation()
annotation.coordinate = coord
annotations.append(annotation)
}
}
completion(annotations) // return array
}
}

我的观点:

ZStack (alignment: .bottom) {
Map(coordinateRegion: $viewModel.region, 
showsUserLocation: true, annotationItems: MKPointAnnotation) { annotations in
MapAnnotation(coordinate: annotations.coordinate) {
Circle()
}
}
.ignoresSafeArea()
.tint(.pink)

LocationButton(.currentLocation) {
viewModel.requestAllowOnceLocationPermission()
}
.foregroundColor(.white)
.cornerRadius(8)
.labelStyle(.iconOnly)
.symbolVariant(.fill)
.tint(.pink)
.padding(.bottom)
.padding(.trailing, 300)
}
.onAppear {
getAnnotations({ (annotations) in
if let annotations = annotations {
print(annotations)
}
})
}

我试着让它成为一个同步函数,但我仍然得到了2个错误。有没有可能先解决这些问题,这样我就可以看看我的getAnnotations函数是否真的有效?

func getAnnotations(...)是异步的,因为内部db.collection("annotations").addSnapshotListener...是异步的。

使用您现在拥有的func getAnnotations(completion: @escaping (_ annotations: [MKPointAnnotation]?) -> Void) {...},并使用以下内容:

.onAppear {
getAnnotations { annotations in
annotations?.forEach { print("----> coordinate: ($0.coordinate)")  }
}
}

注意细节,每个括号都要计数,它们应该如图所示放置。

再次阅读基础知识,网址:https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

并在以下位置执行教程:https://developer.apple.com/tutorials/swiftui/

最新更新