gpt4 book ai didi

ios - 约束协议(protocol)的关联类型本身

转载 作者:行者123 更新时间:2023-11-28 10:17:05 27 4
gpt4 key购买 nike

我正在尝试创建通用 CollectionView 数据源。我有两个协议(protocol),第一个是一些抽象单元,第二个表示符合类可以由某个抽象单元呈现并且应该只包含引用该单元的关联类型。他们的实现可能如下所示:

protocol EntityPresentingCell {

// entity that should be presented in this cell
associatedtype T

static var CellReuseID: String { get }

// takes object and fill UI with data
func populate(with object: T)
}

protocol CellPresentable {

// cell that should present this entity
// I need to constrain it
associatedtype Cell: EntityPresentingCell // where Cell.T == Self
}

class CollectionViewDataSource<T: CellPresentable>: NSObject, UICollectionViewDataSource {

var items: [T]

init(items: [T]) {
self.items = items
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: T.Cell.CellReuseID, for: indexPath)

// compiler error here since, obviously, T.Cell.T not constrained to T itself
(cell as! T.Cell).populate(with: items[indexPath.item])
return cell
}

}

在使用时它看起来像这样:

class SomeEntity: CellPresentable {
typealias Cell = SomeEntityCell

var someValue = "someValue"
}

class SomeEntityCell: EntityPresentingCell {

static var CellReuseID: String = "SomeID"

@IBOutlet weak var label: UILabel!

func populate(with object: SomeEntity) {
label.text = object.someValue
}

}

此代码的问题是我无法约束(因此在编译时确保)CellPresentable.Cell.T 等于 CellPresentable 本身(如示例中所示)。可以清楚地看到编译器错误。

目标是制作纯编译时的全能代码,证明该项目可由给定的单元格呈现(同样,在编译时),我不想强​​制向下转换或任何其他运行时检查.

这可能吗?如果是,怎么办?

更新:David Rodrigues answer有效,但这意味着只有当我要创建 CollectionViewDataSource 时才会显示不匹配 (T.Cell.T != T)。我希望它在我定义我的实体符合 EntityPresentingCell 协议(protocol)时准确发生。换句话说,编译器应该在我写类似的东西时提示

class SomeEntity: CellPresentable {
typealias Cell = SomeWrongEntityCell

var someValue = "someValue"
}

但不是在我创建 CollectionViewDataSource 实例时。实体有责任确保单元格类型,而不是 CollectionViewDataSource 的创建者。

最佳答案

swift 4 更新

您现在可以将 where Cell.T == Self 约束添加到关联类型,因此您现在确实可以说:

protocol CellPresentable {
associatedtype Cell : EntityPresentingCell where Cell.T == Self
}

swift 3

目前,除了关联类型必须符合的条件外,还无法向关联类型添加任何进一步的约束。

但是,现在 SE-0142: Permit where clauses to constrain associated types已被接受,在 Swift 的 future 版本中将有可能向关联类型添加 where 子句。

应该能够说:

protocol CellPresentable {
associatedtype Cell : EntityPresentingCell where Cell.T == Self
}

尽管在实现之前,David's solution添加通用约束 where T.Cell.T == T 可能与您将要获得的一样好。

关于ios - 约束协议(protocol)的关联类型本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067934/

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