[swift-evolution] [Pitch] Add toplevel keyword for protocols

Patrick Pijnappel patrickpijnappel at gmail.com
Fri May 13 02:12:08 CDT 2016


For some protocols we'd like to require top-level (free) functions, e.g.
for many math functions such as abs() or sin(). We already do this
implicitly for operators.

*Proposal*
Allow top-level function/property requirements in protocols, e.g.:

public protocol AbsoluteValuable : SignedNumber { /// Returns the absolute
value of `x`. @warn_unused_result toplevel func abs(_ x: Self) -> Self }

We'd probably want to require this for operators. This also opens up syntax
if we ever get dynamically dispatched operators.


public protocol SignedNumber : Comparable, IntegerLiteralConvertible { ///
Returns the result of negating `x`. @warn_unused_result toplevel prefix func
- (x: Self) -> Self }

Currently this is done using the combination of a static method and a
top-level generic function on that protocol. As I understand that approach
does have some benefits in terms of type-checker performance, though I'm
not sure whether that is likely to stay relevant in the future.

*Advantages*

   - Cleaner than current approach (esp. floating point types have tons of
   top-level functions)
   - Makes operators less of a special case
   - Opens up syntax for member operators
   - Could also apply to top-level properties (esp. useful if we get
   generic properties, for e.g. π<...>)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160513/d09e4535/attachment.html>


More information about the swift-evolution mailing list