[英]Swift: why MKPointAnnotation and not MKAnnotation. Errors out with “'MKAnnotation' cannot be constructed because it has no accessible initializers”
[英]Why do I get this in Swift “cannot be constructed because it has no accessible initializers”
為什么我在 Swift 中得到這個“無法構造,因為它沒有可訪問的初始值設定項”:
import Foundation
protocol Prototype {
func Clone<T>() -> T
}
class myColor: Prototype {
var red: Int?
var green: Int?
var blue: Int?
init () {}
func Clone<myColor>() -> myColor {
let newColor = myColor()
newColor.red = self.red
newColor.green = self.green
newColor.blue = self.blue
return newColor
}
}
錯誤是在線:
let newColor = myColor()
即使您將您的框架設置為公共,您仍然需要將您想要訪問的所有類聲明為“公共”。 您的 init 方法也是如此。
public init() {
}
對我有用。
首先,類有領先的上限。 方法有前導小寫。 你的意思是MyColor
和clone()
。
此時您正在混淆編譯器:
func Clone<myColor>() -> myColor {
它認為您的意思是myColor
是一個隱藏類名的類型變量。 因此,當您使用myColor()
,它與T()
基本相同,它沒有簡單的構造函數。
如果你修復這些東西,你會發現正確的錯誤是
Type 'MyColor' does not conform to protocol 'Prototype'
該錯誤是一個完全不同的問題。 有關如何實現復制協議的說明,請參閱返回 Self 的協議函數。 您可能還對后續內容感興趣: 全局函數上的 Swift 協議和返回類型。
似乎泛型生成類的擴展,並且需要使用。
override init() {...
請注意,Swift 中的任何類都必須具有初始化程序。 並且在您的情況下仍然是通用的,類必須具有init()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.