[swift-evolution] Default implementation for protocols

Howard Lovatt howard.lovatt at gmail.com
Sat Jan 30 18:48:46 CST 2016


Proposal
=======
Allow protocols to define a default implementation, e.g.:

  protocol Complex {
    default var re: Double = 0
    default var im: Double = 0
    var mag: Double { return sqrt(re * re + im * im) }
    // ...
  }

Which gets translated to:

  protocol Complex {
    var re: Double { get,  set }
    var im: Double { get, set }
    var mag: Double { get }
    // ...
  }

  extension Complex {
    var mag: Double { return sqrt(re * re + im * im) }
    // ...
  }

  struct _DefaultComplex: Complex { // Some private name
    var re: Double = 0
    var im: Double = 0
    // ...
  }

In use:

  let complex = Complex()

Gets translated into:

  let complex = _DefaultComplex()


Motivation
========
  1. You often have a default implementation for a protocol, much like a
function argument might have a default value. Therefore this proposal adds
convenience by saving boilerplate.
  2. It is difficult to name a protocol if there is a natural default
implementation. For example the natural name for the protocol that all
integral types inherited from is Integer, but that is also the natural name
for the default implementation. This tension between protocol and default
implementation name leads to strange naming conventions like IntegerType
for the protocol; we already know it is a type (it is a protocol after
all!). This is just a form of Hungarian notation; most people find
Hungarian obfuscates the code rather than clarifying.


Details
=====
  1. Change protocols so that protocol methods are dynamically dispatched,
when overridden in an extension.
  2. Change protocols so that all implementations and overrides of a
protocol method require the override keyword.
  3. Allow protocols to directly specify an implementation as well as via
an extension, also see point 1 and note dynamic dispatch.
  4. Allow via the default keyword protocols to define properties
(including stored), initialisers, and functions that are part of the
default implementation of the protocol but not the protocol itself.
  5. In the case of a default stored property the
  6. Allow the protocol name to be used to call the initialiser and in such
cases use the default implementation.


-- 
  -- Howard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160131/f5226a8b/attachment.html>


More information about the swift-evolution mailing list