[英]Swift func with generic where constraint is a protocol which self conforms
[英]Swift generic protocol function with self
我有一個符合委托協議的通用類。 我希望能夠在協議方法中傳遞self
,但我不知道如何實現。
protocol BodyPartManagerDelegate: class {
func doit(manager: BodyPartManager<Any>)
}
class BodyPartManager<Part> {
weak var delegate: BodyPartManagerDelegate?
var parts: [Part] = []
}
class Neck {}
class NeckManager: BodyPartManager<Neck> {
func doingit() {
delegate?.doit(manager: self)
}
}
使用上面的代碼,我得到的protocol 'BodyPartManagerDelegate' can only be used as a generic constraint because it has Self or associated type requirements
。 如何使用此協議的方法訪問self
?
為了允許將它們中的任何一個傳遞給單個函數,泛型類聲明之間必須具有公共性。 這可以通過聲明所有通用類型的類將支持的另一種協議來實現(例如,在基類中)。
這是一個例子:
protocol BodyPartManagers {} // <-- common protocol for all generic classes
protocol BodyPartManagerDelegate: class
{
func doit(manager: BodyPartManagers)
}
extension BodyPartManagerDelegate
{
func doit(manager: Self) {}
}
class BodyPartManager<Part>:BodyPartManagers // <-- this will make all generic classes compatible
{
weak var delegate: BodyPartManagerDelegate?
var parts: [Part] = []
}
class Neck {}
class NeckManager: BodyPartManager<Neck>
{
func doingit() {
delegate?.doit(manager: self)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.