使用关联类型和自身的Swift协议?

使用关联类型和自身的Swift协议?,swift,Swift,根据本协议: protocol SomeProtocol { associatedtype MyCustomType static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self? } 为什么会这样: extension MyClass: SomeProtocol { static func someCustomStaticFunction(with custom

根据本协议:

protocol SomeProtocol { 
    associatedtype MyCustomType

    static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self?
}
为什么会这样:

extension MyClass: SomeProtocol {
    static func someCustomStaticFunction(with customTypeData: MyCustomType) -> Self? {
        return MyClass()
    }
}
不编译?错误是:
无法将“MyClass”类型的返回表达式转换为返回类型“Self”
。这到底为什么不管用?如果不是这样,那么一开始使用Swift还有什么意义呢?如果我不能建立类型安全协议,而我被迫将其全部删除,那又有什么意义呢?有人能帮我吗

编辑:


问题不是相关类型,而是返回
Self?

您需要将
MyClass
设置为final,并将
MyClass
扩展中返回的
Self
替换为
MyClass

protocol SomeProtocol {
    static func someCustomStaticFunction() -> Self?
}

final class MyClass {

}

extension MyClass: SomeProtocol {
    static func someCustomStaticFunction() -> MyClass? {
        return MyClass()
    }
}
  • 我们只能在协议中使用
    Self
    ,不能使用类扩展

  • 您需要将
    MyClass
    设置为final。如果没有,假设您有一个名为
    MySubclass
    的子类,它还必须确认将
    SomeProtocol
    作为其父类。因此
    MySubclass
    必须具有
    someCustomStaticFunction()->MySubclass
    。但是,
    MyClass
    已经实现了此函数,但返回类型不同。Swift目前不支持重载返回类型,因此,我们不能子类
    MyClass
    ,这是最终的

  • 您需要将
    MyClass
    设置为final,并将
    MyClass
    中返回的
    Self
    扩展名更改为
    MyClass
    可能会在协议中创建一个必需的初始值设定项,并调用该初始值设定项,以便在派生MyClass的情况下返回Self。这在@ukim!你可以把答案贴出来,我会接受的。如果您知道为什么会这样,并且可以提供一个解释,那也太好了:)似乎问题与关联类型无关。如果你愿意,你可以编辑这个问题。