在通用swift对象中约束PAT



是否有一种方法可以约束对象中具有关联类型(PAT(的协议,即不将协议添加到对象的通用列表中。

我的对象已经使用了另一个通用协议(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 ?
}

我知道这样的方法是可行的,但在这种情况下,对象(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
}

你是选择这个还是这个是一个偏好的问题。

struct Foo<Delegate: FooDelegate> {
typealias Item = Delegate.Item
let items: [Item]
var delegate: Delegate
}

最新更新