(if someone can suggest a better title, please do)
The following code does not compile with an error Type 'ObserverClass' does not conform to protocol 'Observer'
, and compiler suggests a fix by declaring var object: ObservedObject
.
class ObservedObject {}
class ObservedObjectSubclass: ObservedObject {}
protocol Observer {
var object: ObservedObject { get }
}
class ObserverClass: Observer { // Type 'ObserverClass' does not conform to protocol 'Observer'
// suggested:
// var object: ObservedObject
var object: ObservedObjectSubclass = ObservedObjectSubclass()
}
The way i see it - ObservedObjectSubclass
is ObservedObject
, and so object
property is guaranteed to be of type ObservedObject
as required by the protocol.
(The same is true, if using protocol conformance instead of subclassing - below)
protocol ObservedObjectProtocol {}
protocol Observer {
var object: ObservedObjectProtocol { get }
}
class ObservedObject: ObservedObjectProtocol {}
class ObserverClass: Observer { // same error
var object: ObservedObject = ObservedObject()
}
Why is compiler unhappy? Is it current limitation, or the compiler is actually right and there is some logical constraint?