【发布时间】:2016-07-29 22:30:11
【问题描述】:
协议P 需要v 类C 的变量。
类X 实现协议P 声明类C1 的变量v,其中C1 扩展C。
代码如下:
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 抱怨此错误:
Type 'X' does not conform to protocol 'P'
Protocol requires property 'v' with type 'C'
Candidate has non-matching type 'C1'
为什么编译器强制我匹配协议中声明的完全相同的类型?
编辑:
在 Obj-C 中完全相同的实现编译时不会出现错误或警告
@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
【问题讨论】:
标签: swift protocols var swift2.2