gpt4 book ai didi

swift - 无法满足协议(protocol)要求

转载 作者:行者123 更新时间:2023-11-28 14:53:10 25 4
gpt4 key购买 nike

我想为 watchOS、iOS 和 TvOS 上的 View 创建一个协议(protocol),这样我就可以以通用方式获取它们的 subview 和父 View 。

起初我试过这个:

protocol ViewProtocol: Hashable {
var superview: Self? { get }
var subviews: [Self] { get }
}

然后我扩展 UIView像这样上课:

extension UIView: ViewProtocol {}

但是我从编译器那里得到这个错误:

<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

我不太明白这个问题(我认为这与编译器无法在非最终类中使用 Self 有关),所以我尝试了以下操作:

协议(protocol)看起来像这样:

protocol ViewProtocol: Hashable {
func getSuperview() -> ViewProtocol?
func getSubviews() -> [ViewProtocol]
}

但现在我在协议(protocol)声明中收到此错误:

Protocol 'ViewProtocol' can only be used as a generic constraint because it has Self or associated type requirements

所以我尝试了这个:

protocol ViewProtocol: Hashable {
func getSuperview<T: ViewProtocol>() -> T?
func getSubviews<T: ViewProtocol>() -> [T]
}

实现看起来像这样:

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]
}
}

但现在当我尝试在泛型类型上使用该方法时 ViewProtocol我收到此错误:Generic parameter 'T' could not be inferred

有人可以帮助我吗?我想从根本上了解这里发生了什么,以及为什么很难做到这一点?

最佳答案

你不能在非 final 类中有 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`
}

关于swift - 无法满足协议(protocol)要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49634486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com