Swift Self as a Bound Type Bound in a Protocol

I want the associated type to be Self, but the compiler does not have it.
Here is what I want to get for compilation:

protocol Protocol {
    // Error: Inheritance from non-protocol, non-class type 'Self'
    associatedtype Type: Self
}

You may ask, why not just use the Selflinked type instead? Just because I cannot: the associated type is inherited from the parent protocol. And it makes no sense to change this in the parent protocol.
Here's something similar to what I'm trying to do:

protocol Factory {
    associatedtype Type

    func new() -> Type
}

protocol SelfFactory: Factory {
    associatedtype Type: Self // Same Error
}

Edit: The
matte answer is almost what I'm looking for. It behaves the way I want it at runtime, but at compile time it is not restrictive enough.
I want this to be impossible:

protocol Factory {
    associatedtype MyType
    static func new() -> MyType
}

protocol SelfFactory: Factory {
    static func new() -> Self
}

final class Class: SelfFactory {

    // Implement SelfFactory:
    static func new() -> Class {
        return Class()
    }

    // But make the Factory implementation diverge:
    typealias MyType = Int

    static func new() -> Int {
        return 0
    }
}

I would like typealiasto Classcause an error re-allocation or the like.

+4
2

?

protocol Factory {
    associatedtype MyType
    func new() -> MyType
}

protocol SelfFactory: Factory {
    func new() -> Self
}
+3

, , Swift 4.0:

protocol Factory {
    associatedtype MyType
    static func new() -> MyType
}

protocol SelfFactory: Factory where MyType == Self { }

?

+2

Source: https://habr.com/ru/post/1651903/


All Articles