[英]Constrain PAT in a generic swift object
有沒有辦法在 object 中約束具有關聯類型 (PAT) 的協議,即不通過將協議添加到 object 的通用列表中。
我的 object 已經使用了另一個通用協議(T:ItemProtocol),它可以用來約束委托 PAT,但我不知道如何做到這一點。
protocol ItemProtocol {
var title: String { get }
}
protocol FooDelegate: AnyObject {
associatedtype Item: ItemProtocol
func foobar(item: Item)
}
struct Foo<T: ItemProtocol> {
// doesn't compile: where clause cannot be attached to a non-generic declaration
typealias Delegate = FooDelegate where Delegate.Item == T
let items: [T]
weak var delegate: Delegate? // how to constrain Delegate.Item == T ?
}
我知道這樣的工作,但在這種情況下 object (Foo) 取決於我不喜歡的委托。
struct Foo<Delegate: FooDelegate> {
let items: [Delegate.Item]
weak var delegate: Delegate?
}
不可能在類型聲明“內”執行此操作。 所有通用占位符和約束都需要存在於類型聲明中(受約束的擴展除外)。
但是,編譯器並不認為定義與另一個通用占位符的關聯類型相同的通用占位符是多余的。
struct Foo<Item, Delegate: FooDelegate> where Item == Delegate.Item {
let items: [Item]
var delegate: Delegate
}
無論您是 go 還是這是一個偏好問題。
struct Foo<Delegate: FooDelegate> {
typealias Item = Delegate.Item
let items: [Item]
var delegate: Delegate
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.