[swift-evolution] [RFD] Non-Self Protocol Requirements

Erica Sadun erica at ericasadun.com
Mon May 16 09:15:33 CDT 2016


The following situation has come up for me now and then: I want to work with groups of types that share a common behavior, but that behavior is not sourced in the implementation of the Self type but rather in a secondary type.  Specifically, could Swift be extended to introduce a protocol requirement that discusses how a type is used by a secondary type and not the kind of member provided directly by the type. For example:

// These are all numbers
let int32: Int32 = 1; let int8: Int8 = 1
let double: Double = 1.0; let cgfloat: CGFloat = 1.0; let float: Float = 1

// They can all be converted to Double using Double.init
Double(int32); Double(int8); Double(double); Double(cgfloat); Double(float)

// A heterogeneous collection cannot be unified into a single protocol
let foo: [Any] = [int32, int8, double, cgfloat, float]
foo.map{ Double($0) } // Can't work, Any doesn't make any sense here

The kind of thing I am looking for is something like this:

protocol DoubleSource {
    Double.init(Self)
}

In other words, the functionality constraint is not provided by the base type but by a second type to which the base type is a parameter.

My use case is for unrelated types (that is, there's no inheritance relationship like you'd find in `UISwitch` and `UISlider`, for example -- both of which are `UIView` and `UIControl`), where there is a secondary type that implements behavior with the same signature for these separate types, such as the Double initializer. Where this pops up the most is in working with Sprite/SceneKit, GamePlayKit, QuartzCore, Accelerate, unifying my numeric values so I can mix and match calls and clean up the flow where some calls require CGPoint, others need float2, etc. Ideally I would be able to 

extension DoubleSource {
    func bar() -> T {
        let value = Double.init(self)
        // do something with value; return T of some type
    }
}

let foo: [DoubleSource] = [int32, int8, double, cgfloat, float]
foo.map{ bar($0) } // would work

Would something like this be a valuable direction to extend Swift? Is it something found in other languages? Does this kind of requirement have a name? Is it *pragmatically* possible to introduce it in Swift?

Thanks in advance for your thoughts and insights.

-- E

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


More information about the swift-evolution mailing list