簡體   English   中英

使用關聯類型和Self的Swift協議?

[英]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()
    }
}
  1. 我們只能使用Self in協議,而不能使用類擴展。
  2. 您需要將MyClass最終版本。 否則,假設您有一個名為MySubclass的子類,它還必須確認SomeProtocol作為其父類。 因此, MySubclass必須具有someCustomStaticFunction() -> MySubclass 但是, MyClass已經實現了此功能,但返回類型不同。 Swift目前不支持重載返回類型,因此,我們一定不能繼承MyClass ,這使其成為最終的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM