[swift-evolution] [Pitch] Non-class type requirements on protocols (eg : struct, : enum)
Adrian Zubarev
adrian.zubarev at devandartist.com
Fri Oct 21 03:25:23 CDT 2016
We had similar talks about that topic before. There is a thread somewhere on this, but it’s mainly focused on value type semantics.
If I remember correctly we might even discussed to remove the class constraint completely from the language and introduce a protocol solution to this problem.
There are also some words about the class constraint in the GenericsManifesto.md
Generalized class constraints
The class constraint can currently only be used for defining protocols. We could generalize it to associated type and type parameter declarations, e.g.,
protocol P {
associatedtype A : class
}
func foo<T : class>(t: T) { }
As part of this, the magical AnyObject protocol could be replaced with an existential with a class bound, so that it becomes a typealias:
typealias AnyObject = protocol<class>
See the “Existentials” section, particularly “Generalized existentials”, for more information.
Instead of : class we might use : AnyObject as a constraint (or : AnyReference?).
Instead of : struct/enum we should have something like : value or even better : AnyValue.
I believe we should focus on existential types first before fixing this gap in Swift. Any<T> might receive the mentioned constraints and could create something like this:
typealias AnyObject = Any<class>
typealias AnyValue = Any<value>
--
Adrian Zubarev
Sent with Airmail
Am 21. Oktober 2016 um 08:55:40, Xiaodi Wu via swift-evolution (swift-evolution at swift.org) schrieb:
What's your use case for distinguishing structs and enums?
On Fri, Oct 21, 2016 at 1:40 AM Mike Kasianowicz via swift-evolution <swift-evolution at swift.org> wrote:
Currently protocols can have the class constraint:
protocol MyProtocol : class {}
It would be (a) intuitive and (b) useful to allow such things as:
protocol Model : struct {} or protocol Event : enum {}
These types of restrictions can help prevent accidental anti-patterns or misuse of APIs.
Seems simple and non-controversial... right?
[Note: I'd like to see even more heavy-handed protocol restrictions in the future. For example, a protocol describing an enum with a common case, or a struct with no reference members. Great stuff for defensively coding APIs.]
_______________________________________________
swift-evolution mailing list
swift-evolution at swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution
_______________________________________________
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/20161021/70672dd6/attachment.html>
More information about the swift-evolution
mailing list