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?