[swift-evolution] Abstract methods
Brent Royal-Gordon
brent at architechies.com
Thu Nov 2 22:29:31 CDT 2017
> On Nov 2, 2017, at 1:57 PM, Taylor Swift via swift-evolution <swift-evolution at swift.org> wrote:
>
> Swift architectures use much less inheritance (and class types) in general than equivalent c++ architectures. personally i have never been in a situation where i didn’t need a pure abstract method that was better declared as a protocol requirement.
I think we should beef up protocols a little bit so that they can serve the role of abstract classes. That would make for a nice, clean separation: anything abstract is a protocol, while anything concrete is a class (or struct or enum).
What would protocols need in order to support everything abstract classes can do? First, we'd probably need to extend class constraints to allow a protocol to require you to subclass a given base class:
// Hypothetical replacement for UIControl.
protocol UIControl: UIView {
func sendAction(_ action: Selector, to target: Any?, for event: UIEvent)
}
extension UIControl {
func sendAction(_ action: Selector, to target: Any?, for event: UIEvent) {
UIApplication.shared.sendAction(action, to: target, from: self, for: event)
}
}
Maybe allow them to declare automatically-added storage, perhaps even private to the protocol:
protocol UIControl: UIView {
@automatic
private var actions: [UIControlEvents: [(target: Any?, action: Selector)]] = [:]
func sendAction(_ action: Selector, to target: Any?, for event: UIEvent)
}
extension UIControl {
func sendActions(for controlEvents: UIControlEvents) {
for (event, pairs) in actions where event.contains(controlEvents) {
for pair in pairs {
sendAction(pair.action, to: pair.target, for: UIApplication.shared.currentEvent)
}
}
}
func sendAction(_ action: Selector, to target: Any?, for event: UIEvent) {
UIApplication.shared.sendAction(action, to: target, from: self, for: event)
}
}
Probably something like `super` for when you want to override a default implementation but still call it:
class MyButton: UIControl {
func sendAction(_ action: Selector, to target: Any?, for event: UIEvent) {
print("Sending \(action) to \(target)")
super(UIControl).sendAction(action, to: target, for: event)
}
}
These are all solid features that would be great additions to protocols, even when they're *not* replacing abstract classes.
--
Brent Royal-Gordon
Architechies
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171102/79b16d1f/attachment.html>
More information about the swift-evolution
mailing list