A protocol P requires a variable v of class C.
Class X implements protocol P declaring a variable v of class C1 where C1 extends C.
Here's the code:
import Foundation
class C { }
class C1: C { }
protocol P {
var v: C { get set }
}
class X: P {
var v: C1
init(withV v: C1) {
self.v = v
}
}
Xcode complaints with this error:
Type 'X' does not conform to protocol 'P'
Protocol requires property 'v' with type 'C'
Candidate has non-matching type 'C1'
Why is the compiler forcing me to match exactly the same type declared in the protocol?
Edit:
The exact same implementation in Obj-C compiles without errors or warnings
@interface C: NSObject
@end
@implementation C
@end
@interface C1: C
@end
@implementation C1
@end
@protocol P <NSObject>
@property (nonatomic, strong) C *v;
@end
@interface X: NSObject <P>
@property (nonatomic, strong) C1 *v;
@end
@implementation X
@end
It isn't forcing you to match exactly, but it's forcing you to avoid runtime issues. Your setup can mean that you pass a reference to something claiming to conform to P but which doesn't actually conform. This is because P says that you can set v to any C, but X says you can set v to any C1.
So, if you were to create another subclass of C, C2, and try to use that, everything would fall apart.
I'd expect your obj-c example to complain that you haven't implemented or synthesised the property specified to exist in the protocol...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With