[swift-evolution] [Proposal] Allow static protocol extension methods to be called directly on the protocol

Joe Groff jgroff at apple.com
Sat Feb 27 19:05:52 CST 2016


Rasmus Kjeldsen via swift-evolution
<swift-evolution at swift.org> wrote:
> 
> I propose to allow static protocol extension methods to be used directly on the protocol.
> This would enable the Factory-pattern to be elegantly implemented as in the example below:
> 
> protocol P {}
> 
> class A : P {}
> class B : P {}
> 
> extension P {
> 	static func factory(type: Bool) -> P { return type ? A() : B()}
> }
> 
> let a = P.factory(false) // <- Not possible in Swift 2, factory() can
> only be used on either A or B
> 
> Regards
> 
> Rasmus Friis Kjeldsen
> 
> 
> 
> 

'extension P' extends all types that conform to P. We could introduce a new
syntax for extending the protocol type, maybe:

extension protocol<P> { ... }

This might be an important part of fleshing out our support for protocol
existential types. It would offer a way for protocol types to conform to
their own protocols even when Self or associated types make that normally
impossible. 

-Joe 




More information about the swift-evolution mailing list