Swift 是否在协议变量中严格执行 Class?
is Swift strictly enforcing Class in protocol vars?
协议 P
需要 class C
的变量 v
。
Class X
实现协议 P
声明变量 v
of class C1
where C1
extends 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
它不是强制您完全匹配,而是强制您避免运行时问题。您的设置可能意味着您传递了对声称符合 P
但实际上并不符合的内容的引用。这是因为 P
表示您可以将 v
设置为任何 C
,但是 X
表示您可以将 v
设置为任何 C1
。
因此,如果您要创建 C
、C2
的另一个子类并尝试使用它,一切都会崩溃。
我希望您的 obj-c 示例抱怨您没有实现或综合协议中指定存在的 属性...
协议 P
需要 class C
的变量 v
。
Class X
实现协议 P
声明变量 v
of class C1
where C1
extends 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
它不是强制您完全匹配,而是强制您避免运行时问题。您的设置可能意味着您传递了对声称符合 P
但实际上并不符合的内容的引用。这是因为 P
表示您可以将 v
设置为任何 C
,但是 X
表示您可以将 v
设置为任何 C1
。
因此,如果您要创建 C
、C2
的另一个子类并尝试使用它,一切都会崩溃。
我希望您的 obj-c 示例抱怨您没有实现或综合协议中指定存在的 属性...