简体   繁体   English

在通用 swift object 中约束 PAT

[英]Constrain PAT in a generic swift object

Is there a way to constrain a protocol with associated type (PAT) within an object, ie not by adding the protocol to the generic list of the object.有没有办法在 object 中约束具有关联类型 (PAT) 的协议,即不通过将协议添加到 object 的通用列表中。

My object already uses another generic protocol (T: ItemProtocol) that could be used to constrain the delegate PAT but I don't see how this has to be done.我的 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 ?
}

I know something like this works, but in this case the object (Foo) depends on the delegate which I don't like.我知道这样的工作,但在这种情况下 object (Foo) 取决于我不喜欢的委托。

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

It is not possible to do this "within" a type declaration.不可能在类型声明“内”执行此操作。 All of the generic placeholders and constraints need to exist in the type declaration (except for constrained extensions).所有通用占位符和约束都需要存在于类型声明中(受约束的扩展除外)。

However, the compiler does not consider it to be redundant to define a generic placeholder that is the same type as an associated type of another generic placeholder.但是,编译器并不认为定义与另一个通用占位符的关联类型相同的通用占位符是多余的。

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

Whether you go with that or this is a matter of preference.无论您是 go 还是这是一个偏好问题。

struct Foo<Delegate: FooDelegate> {
  typealias Item = Delegate.Item

  let items: [Item]
  var delegate: Delegate
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM