簡體   English   中英

Protocol '...' as a type cannot conform to '...' - 泛型協議問題的泛型協議

[英]Protocol '...' as a type cannot conform to '...' - A generic protocol of a generic protocol issue

我一直在玩 Swift 和 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”

在 Swift 5.7 下,我得到一個稍微不同的錯誤

類型“任何 OtherDelegateProtocol”不能符合“SomeDelegateProtocol”

只是為了(一點點)清晰。 大多數應用程序代碼將使用SomeManager的實現,例如,需要處理OtherItemProtocol的代碼將直接通過OtherManager工作,而不關心實體的“如何”存儲。 這種方法旨在減少“重復”代碼的數量。

我花了幾天時間試圖解決這個問題,但我似乎找不到與這個特定問題相匹配的解決方案。 我可能會在角落里哭一會兒......如果有人對我如何解決這個問題有一些想法,我會很感激😭

(是的,我一直在谷歌搜索,但我沒有找到任何與我“夢想”的類似結構相匹配的東西)

迅速迅速

你寫的是簡寫

class OtherManager: SomeManager<any OtherDelegateProtocol> { }

但是協議不符合它們自己。 any OtherDelegateProtocol都不符合: SomeDelegateProtocol要求。 相反,您需要一個具體的SomeDelegateProtocol類型。

表達這一點:

class OtherManager<Delegate: OtherDelegateProtocol>: SomeManager<Delegate> {

此外, Item == any OtherItemProtocol感覺就像 Objective-C 代碼。 也許你是這個意思?

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 {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM