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

Leonardo Pessoa me at lmpessoa.com
Fri May 13 11:26:38 CDT 2016


To me this makes more sense for operators than for other functions or
properties. For the former you could create conflict with previously
declared function (or properties with variables) and there is no
restriction in Swift that says you cannot or should not create a top level
function or property.

In this sense, having an operator declared inside a class/struct/enum would
already make them top level as you proposed, no need for another keyword. I
would only add one requirement: that the first argument should always be of
type Self (and have it checked by the compiler). It ensures the operator
operates on that type and helps minimising conflicts with a previously
declared operator.

- Leonardo

On 13 May 2016 at 04:12, Patrick Pijnappel via swift-evolution <
swift-evolution at swift.org> wrote:

> 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. π<...>)
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160513/fc76c7e4/attachment.html>


More information about the swift-evolution mailing list