[英]Swift Protocol using associated types and Self?
鑒於此協議:
protocol SomeProtocol {
associatedtype MyCustomType
static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self?
}
為什么這樣做:
extension MyClass: SomeProtocol {
static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self? {
return MyClass()
}
}
無法編譯? 錯誤是: cannot convert return expression of type 'MyClass" to return type "Self?
。 為什么這根本行不通? 如果沒有,那么即使首先使用Swift也有什么意義呢? 如果我無法建立類型安全的協議,而無論如何我都不得不對其進行類型擦除,那有什么意義呢? 有人可以幫我嗎?
編輯:
問題不是關聯的類型,而是返回Self?
您需要將MyClass
最終版本,並將MyClass
擴展名中返回的Self
替換為MyClass
。
protocol SomeProtocol {
static func someCustomStaticFunction() -> Self?
}
final class MyClass {
}
extension MyClass: SomeProtocol {
static func someCustomStaticFunction() -> MyClass? {
return MyClass()
}
}
Self
in協議,而不能使用類擴展。 MyClass
最終版本。 否則,假設您有一個名為MySubclass
的子類,它還必須確認SomeProtocol
作為其父類。 因此, MySubclass
必須具有someCustomStaticFunction() -> MySubclass
。 但是, MyClass
已經實現了此功能,但返回類型不同。 Swift目前不支持重載返回類型,因此,我們一定不能繼承MyClass
,這使其成為最終的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.