[swift-evolution] [Idea] How to eliminate 'optional' protocol requirements

Антон Жилин antonyzhilin at gmail.com
Sat Apr 9 14:41:00 CDT 2016


Here is how I would like this to be implemented.

1. Optional method requirements will be represented in Swift as methods
having import-only attribute @optional and defaulted to be fatalError()

2. On the inside, this default implementation will not define a method.
These objects will not respond to corresponding selector unless the default
implementation is overridden.

3. Calls from Swift side will turn into checks with fatalError()

4. The only way to check existence of such method from Swift will be
`responds(to: Selector)`

Example:

// Objective-C protocol is imported as:
protocol NSTableViewDelegate {
@optional func tableView(_: NSTableView, viewFor: NSTableColumn, row: Int)
-> NSView?
@optional func tableView(_: NSTableView, heightOfRow: Int) -> CGFloat
}
extension NSTableViewDelegate {
@optional func tableView(_: NSTableView, viewFor: NSTableColumn, row: Int)
-> NSView? {
fatalError("Unimplemented")
}
@optional func tableView(_: NSTableView, heightOfRow: Int) -> CGFloat {
fatalError("Unimplemented")
}
}

class MyDelegate : NSTableViewDelegate {
@optional func tableView(_: NSTableView, viewFor: NSTableColumn, row: Int)
-> NSView? {
//...
}
}

getTableViewDelegate().tableView(x, heightOfRow: y) // will fatalError() if
not responds to selector
if getTableViewDelegate().responds(to: #selector(...)) { ... }

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


More information about the swift-evolution mailing list