[swift-evolution] PITCH: Return a subclass for a protocol method without the need for an associatedtype

Sitton, Yogev Yogev_Sitton at intuit.com
Wed Aug 17 02:09:37 CDT 2016


Hi,

I raised this issue a few months back and discussion has died out since.
I’m raising this again to see if there are any objections before I submit a proposal.



I have a class that conforms to a protocol which declares a method with a specific return type.
In case I want to return a subclass of the return type I am forced to use anassociatedtype.
This feels like a hack.

Example:

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

// Circle inherits from Shape
class Circle : Shape {}

// CircleMaker conforms to the MyShapeProtocol
class CircleMaker : MyShapeProtocol {
// CircleMaker wants to return Circle which is a type of Shape
func make() ->Circle? {
return Circle()
}
}

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

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

class Circle : Shape {}

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

What I’m suggesting is to allow to return a subclass for a protocol method without the need for an associatedtype.

Any reason why not?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160817/7fb4fe81/attachment.html>


More information about the swift-evolution mailing list