[英]Why do I get this in Swift “cannot be constructed because it has no accessible initializers”
[英]Swift: why MKPointAnnotation and not MKAnnotation. Errors out with “'MKAnnotation' cannot be constructed because it has no accessible initializers”
為了在Swift中的地圖視圖中添加注釋,我可以使用以下代碼,例如:
讓myLocation = CLLocationCoordinate2D(55.55,-77.77)
let annotation = MKPointAnnotation()
annotation.coordinate = myLocation
annotation.title = "Some place"
map.addAnnotation(annotation)
但是我的問題是,map.addAnnotation的類型為“ MKAnnotation”,而不是“ MKPointAnnotation”,如下所示。 map.addAnnotation(注釋:MKAnnotation)
並且如果我創建一個MKAnnotation的實例,即讓注釋= MKAnnotation(),則會收到錯誤消息“無法構造'MKAnnotation',因為它沒有可訪問的初始化程序”,並且無法設置諸如批注.coordinate或title等屬性。
那么,為什么不進行這項工作呢?myLocation = CLLocationCoordinate2D(55.55,-77.77)
let annotation = MKAnnotation() //error
annotation.coordinate = myLocation //property not accessible
annotation.title = "Some place" //property not accessible
map.addAnnotation(annotation)
MKAnnotation
是協議,而不是類,因此您不能直接實例化它,只能實例化符合它的類。 MKPointAnnotation
是一個類,並且確實符合MKAnnotation
協議,因此您可以實例化並直接使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.