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

时间:2018-08-03 22:07:01

标签: swift

给出以下协议:

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?

1 个答案:

答案 0 :(得分:1)

您需要使MyClass最终定下来,并将Self扩展名中返回的MyClass替换为MyClass

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

final class MyClass {

}

extension MyClass: SomeProtocol {
    static func someCustomStaticFunction() -> MyClass? {
        return MyClass()
    }
}
  1. 我们只能在协议中使用Self,而不能在类扩展中使用。
  2. 您需要完成MyClass的定稿。否则,假设您有一个名为MySubclass的子类,它也必须确认SomeProtocol作为其父类。因此MySubclass必须具有someCustomStaticFunction() -> MySubclass。但是,MyClass已经实现了此功能,但是返回类型不同。 Swift目前不支持重载返回类型,因此,我们绝对不能继承MyClass的子类,这使它成为最终的。
相关问题