gpt4 book ai didi

swift - 实现存储库模式时避免类型删除

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:15 25 4
gpt4 key购买 nike

我正在尝试以通用方式在 Swift 中实现存储库模式。我目前面临的问题是,似乎我必须为我的所有存储库编写类型删除包装器。我在这里错过了什么吗?此时是否有更好的方法来执行此操作或让编译器满意?

// 1
class Item {}

// 2
protocol Repository {
associatedtype T
}

// 3
protocol AnyItemRepository: Repository where T == Item {}

// 4
class ItemRepository: AnyItemRepository {
static let shared = ItemRepository()

private init() {}
}

// 5
class ViewController {

// 6
var itemRepository: AnyItemRepository? = ItemRepository.shared

}
  1. 众多实体之一
  2. 必要时可以扩展或直接实现的基本存储库接口(interface)
  3. 一个特殊的项目存储库接口(interface),保证在基本存储库之上提供额外的功能
  4. 特定实体类型的具体存储库实现
  5. 一些需要访问数据的类
  6. 对任何项目存储库的依赖性。此行的编译器错误:Protocol 'AnyItemRepository' can only be used as a generic constraint because it has Self or associated type requirements

最佳答案

您不需要 AnyItemRepository 类型。只需在 Repository 上编写扩展方法,如下所示:

public extension Repository where T == Item {
func doSomethingSpecial(with items: [Item]) {
// blah blah
}
}

在您的 View Controller 中,您不能以这种方式使用RepositoryAnyItemRepository,因为它们是通用类型约束。您必须使用具体类型或一般参数化 ViewController

class RepositoryViewController<R>: UIViewController where R: Repository, R.T == Item {
var itemRepository: R { get }
}

class ViewController: RepositoryViewController<ItemRepository> {
override var itemRepository: ItemRepository {
return ItemRepository.shared
}
}

(以上是未经测试的伪代码,旨在为您提供要点。它从未被任何人运行过,甚至可能无法编译。)

关于swift - 实现存储库模式时避免类型删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549318/

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