[swift-evolution] Specified Protocol Conformances in Subclasses

Rob Mayoff mayoff at dqd.com
Fri Mar 10 13:32:26 CST 2017


On Fri, Mar 10, 2017 at 6:08 AM, Rod Brown via swift-evolution <
swift-evolution at swift.org> wrote:

> Hi everyone. I found something odd that seems baked into how Cocoa Touch
> does protocols, but Swift cannot model it:
>
>
> @interface UIScrollView: UIView
>
> @property (weak, nonatomic) id <UIScrollViewDelegate> delegate;
>
> @end
>
> @interface UITableView: UIScrollView
>
> @property (weak, nonatomic) id <UITableViewDelegate> delegate;
>
> @end
>
> @protocol UITableViewDelegate: UIScrollViewDelegate
> ...
> @end
>

The problem here is that `UITableView`'s redefinition of `delegate` is not
type-safe. By casting a `UITableView` reference to a `UIScrollView`, you
set the `delegate` to something that doesn't conform to `UITableView`:

    @interface ViewController () <UIScrollViewDelegate>
    @end

    @implementation ViewController

    - (void)viewDidLoad {
        [super viewDidLoad];

        UITableView *tableView = [[UITableView alloc] init];

        // This line correctly generates a warning, because self isn't a
UITableViewDelegate:
        tableView.delegate = self;

        // This line generates no warning:
        ((UIScrollView *)tableView).delegate = self;
    }

    @end
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170310/e30ba8fa/attachment.html>


More information about the swift-evolution mailing list