我一直在和斯威夫特和SwiftUI一起玩。我一直在尝试为各种“数据实体”设计一个基于委托的数据存储,目的是在保持代码接口稳定的同时,能够替换底层的数据存储实现(这是一个实验性的代码库,因此我希望随着时间的推移使用不同的数据存储)。
经过几次尝试,我得出的结论是,大部分顶级工作都是重复的(我最终基本上要处理的是粘贴锅炉板代码),所以,我认为我会变得聪明,减少并重复使用这些概念,愚蠢的我。
因此,我从一个基本委托开始,它保存每个委托都需要完成的“核心”/“公共”功能。
protocol SomeDelegateProtocol {
associatedtype Item
func performActionOn(_ item: Item)
// Lots of common actions which can
// be performed on entities
}再加上一个“公共”顶级管理器的概念(应用程序将完成的实现--因此我们正在将这些层解耦)
class SomeManager<Delegate: SomeDelegateProtocol> {
typealias Item = Delegate.Item
let delegate: Delegate
@Published var items: [Delegate.Item]
// Other properties
init(delegate: Delegate) {
self.delegate = delegate
}
// Lots of boiler plate functionality
}现在,对于每个实体,我们需要定义一个目标委托和管理器。
protocol OtherItemProtocol {
// Item enity properties
}
protocol OtherDelegateProtocol: SomeDelegateProtocol where Item == any OtherItemProtocol {
// Specific functionality for this delegate
}
class OtherManager: SomeManager<OtherDelegateProtocol> {
// Specific functionality for type of manager
}这就是我遇到问题的地方。在我的OtherManager上,Xcode/Swift抱怨说:
协议“OtherDelegateProtocol”作为一种类型不能符合“SomeDelegateProtocol”
在SWIFT5.7下,我得到了一个稍微不同的错误
类型“任意OtherDelegateProtocol”不能符合“SomeDelegateProtocol`”
只是为了(一点点)清晰。大多数应用程序代码将使用SomeManager的实现,例如,需要处理OtherItemProtocol的代码将直接通过OtherManager工作,而不关心实体是如何存储的。这种方法的目的是减少“重复”代码的数量。
我花了几天的时间试图解决这个问题,但我似乎找不到一个与这个问题相匹配的解决方案。我可能会在角落里哭一会儿.如果有人对我如何解决这个问题有一些想法,我会很感激的。
(是的,我一直在谷歌上搜索,但我没有发现任何与我“梦寐以求”的模拟结构相匹配的东西)
发布于 2022-06-25 02:17:39
你写的是
class OtherManager: SomeManager<any OtherDelegateProtocol> { }但协议不符合自己的要求。any OtherDelegateProtocol不符合: SomeDelegateProtocol要求。相反,您需要一个具体的SomeDelegateProtocol类型。
表示:
class OtherManager<Delegate: OtherDelegateProtocol>: SomeManager<Delegate> {而且,Item == any OtherItemProtocol感觉就像Objective代码。也许你是说这个?
protocol OtherDelegateProtocol: SomeDelegateProtocol where Item: OtherItemProtocol {你是否需要OtherDelegateProtocol,而不是一个扩展?
extension SomeDelegateProtocol where Item: OtherItemProtocol {class OtherManager<Delegate: SomeDelegateProtocol>: SomeManager<Delegate> where Delegate.Item: OtherItemProtocol {你需要子类吗?通常,没有人需要Swift中的子类。
extension SomeManager where Item: OtherItemProtocol {https://stackoverflow.com/questions/72750052
复制相似问题