代码之家  ›  专栏  ›  技术社区  ›  barndog

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

  •  0
  • barndog  · 技术社区  · 7 年前

    根据本协议:

    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 回复  |  直到 7 年前
        1
  •  1
  •   ukim    7 年前

    你需要 MyClass 最终并替换 Self 返回 类名 扩展名 类名 .

    protocol SomeProtocol {
        static func someCustomStaticFunction() -> Self?
    }
    
    final class MyClass {
    
    }
    
    extension MyClass: SomeProtocol {
        static func someCustomStaticFunction() -> MyClass? {
            return MyClass()
        }
    }
    
    1. 我们只能用 自我 在协议中,但不在类扩展中。
    2. 你需要 类名 最后。如果不是,假设你有一个名为 MySubclass ,它还必须确认 SomeProtocol 作为它的父母。所以 我的子类 一定有 someCustomStaticFunction() -> MySubclass . 然而, 类名 已实现此函数,但返回类型不同。Swift目前不支持重载返回类型,因此,我们不能子类化 类名 ,这是最后的决定。