[swift-evolution] [PROPOSAL]Return subclass type to a protocol where a superclass is defined without the need for associatedtype

Yogev Sitton yogev.sitton at gmail.com
Sun Apr 17 03:52:41 CDT 2016


I have a class that is conforming to a protocol with a method that requires a specific return type.
In case I want to return a subclass of the return type I am forced to use an associatedtype that feels like a hack.

As an example:

protocol MyShapeProtocol {
    func make() -> Shape?
}

class Circle : Shape {}

class CircleMaker : MyShapeProtocol{
    func make() -> Circle? {
        return Circle()
    }
}

This will not work.
For that to work I’ll need to use toe associatedtype “hack”:

protocol MyShapeProtocol {
    associatedtype ShapeReturnType : Shape
    func make() -> ShapeReturnType?
}

class Circle : Shape {}

class CircleMaker : MyShapeProtocol{
    func make() -> Circle? {
        return Circle()
    }
}

Is there a real value in adding the associatedtype line?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160417/ce1d8f04/attachment.html>


More information about the swift-evolution mailing list