假设我有两个协议:
@protocol A
@end
和
@protocol B <A> // Protocol B conforms to protocol A.
@end
还有两个变量:
id<A> myVar = nil;
和
id<B> otherVar = //correctly initialized to some class that conforms to <B>;
然后,为什么不能将“otherVar”分配给“myVar”?
myVar = otherVar; //Warning, sending id<B> to parameter of incompatible type id<A>
谢谢!
最佳答案
协议的(B
)声明(不仅仅是其前向声明)是否可见?声明是否在myVar = otherVar;
之前?
当声明顺序正确时,clang没有抱怨。
为了显示:
@protocol A
@end
@protocol B; // << forward B
void fn() {
id<A> myVar = nil;
id<B> otherVar = nil;
myVar = otherVar; // << warning
}
// declaration follows use, or is not visible:
@protocol B <A>
@end
而正确订购的版本不会产生警告:
@protocol A
@end
@protocol B <A>
@end
void fn() {
id<A> myVar = nil;
id<B> otherVar = nil;
myVar = otherVar;
}