0

I have this code:

import UIKit

protocol ProtocolA {
    associatedtype View: ProtocolB
    var someView: View { get }
}

protocol ProtocolB { }

class MyView: UIView, ProtocolB {}

class MyClass: ProtocolA {
    var someView = MyView()
}

This compiles. MyView conforms to ProtocolB, and therefore is a ProtocolB. MyClass conforms to ProtocolA because it has a ProtocolB as property. So far so good.

But why is the associated type necessary here for the code to compile? Why does this not compile?

import UIKit

protocol ProtocolA {
    var someView: ProtocolB { get }
}

protocol ProtocolB { }

class MyView: UIView, ProtocolB {}

class MyClass: ProtocolA { // Error here, it doesn't conform to ProtocolA.
    var someView = MyView()
}

Why?! MyView is still a ProtocolB right? I can fix this by doing this:

var someView: ProtocolB = MyView()

But that's strange because MyView is always ProtocolB. I also can't access any property defined in MyView now.

What is the difference between two codes? It looks like they are really the same. Why does the associated type allows subclasses, why the 'normal' type doesn't?

J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • 2
    Compare https://stackoverflow.com/q/42561685/2976878 – there's no technical reason why your second example shouldn't work. – Hamish Nov 28 '18 at 19:16
  • @Hamish I think you answered every possible protocol question about Swift on SO :D – J. Doe Nov 28 '18 at 19:21
  • I've certainly tried my best :) Are you happy with marking this as a duplicate of that Q&A? – Hamish Nov 28 '18 at 19:31
  • @Hamish yes you can close this one! Thank you for all of your efforts to this community! – J. Doe Nov 28 '18 at 20:48

0 Answers0