[英]Protocol requirement cannot be satisfied
I would like to create a protocol for view on watchOS, iOS and TvOS, so I can get their subviews and superviews in a generic way. 我想为watchOS,iOS和TvOS上的视图创建一个协议,因此可以以通用方式获取其子视图和超级视图。
At first I tried this : 一开始我尝试了这个:
protocol ViewProtocol: Hashable {
var superview: Self? { get }
var subviews: [Self] { get }
}
And then I extend the UIView
class like this : 然后我像这样扩展UIView
类:
extension UIView: ViewProtocol {}
But I get this error from the compiler: 但是我从编译器得到这个错误:
<unknown>:0: error: protocol 'ViewProtocol' requirement 'superview' cannot be satisfied by a non-final class ('UIView') because it uses 'Self' in a non-parameter, non-result type position
I'm not sur to understand the problem (I think it's related to the compiler not being able to use Self in a non final class), so I tried the following : 我不了解这个问题(我认为这与编译器无法在非最终类中使用Self有关),因此我尝试了以下操作:
The protocol would look like this : 该协议如下所示:
protocol ViewProtocol: Hashable {
func getSuperview() -> ViewProtocol?
func getSubviews() -> [ViewProtocol]
}
But now I get this error at the protocol declaration : 但是现在我在协议声明中得到了这个错误:
Protocol 'ViewProtocol' can only be used as a generic constraint because it has Self or associated type requirements
So I tried this : 所以我尝试了这个:
protocol ViewProtocol: Hashable {
func getSuperview<T: ViewProtocol>() -> T?
func getSubviews<T: ViewProtocol>() -> [T]
}
And the implementation look like this: 实现看起来像这样:
extension UIView: ViewProtocol {
func getSuperview<T>() -> T? where T : ViewProtocol {
return self.superview as! T?
}
func getSubviews<T>() -> [T] where T : ViewProtocol {
return self.subviews as! [T]
}
}
But now when I try to use the method on generic type ViewProtocol
I get this error : Generic parameter 'T' could not be inferred
但是现在当我尝试在通用类型ViewProtocol
上使用该方法时,出现此错误: Generic parameter 'T' could not be inferred
Can someone help me ? 有人能帮我吗 ? I would like to fundamentally understand what's going on here and why it is so difficult to make that work ? 我想从根本上了解这里发生的事情以及为什么很难进行这项工作?
You can't have a Self
requirement in non-final classes, and here's an example to illustrate why that wouldn't make sense: 您不能在非最终课程中使用“ Self
要求,这是一个示例来说明为什么这样做没有意义:
protocol Copyable {
var copyOfSelf: Self { get }
}
final class Car {
let name: String
init(name: String) { self.name = name }
}
extension Car: Copyable {
var copyOfSelf: Car { return Car(name: self.name) }
}
class SportsCar: Car {
// Inherited:
// var copyOfSelf: Car { return Car(name: self.name) }
// Notice that it still returns `Car`, not `SportsCar`,
// Breaking the conformance to `Copyable`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.