我正在嘗試使我的 SwiftUI 視圖更加“可預覽”,因此我將它們在其 Store (ViewModel) 上通用化,以便我可以更輕松地模擬它們。
考慮以下示例:
public protocol HomeViewStore: ObservableObject {
associatedtype AnimatableImageStoreType = AnimatableImageStore
var title: String { get }
var animatableImageStores: [AnimatableImageStoreType] { get }
var buttonTapSubject: PassthroughSubject<Void, Never> { get }
var retryTapSubject: PassthroughSubject<Void, Never> { get }
}
public protocol AnimatableImageStore: ObservableObject, Identifiable {
var imageConvertible: Data? { get }
var onAppear: PassthroughSubject<Void, Never> { get }
}
struct AnimatableImage<
AnimatableImageStoreType: AnimatableImageStore
>: View {
@ObservedObject private var store: AnimatableImageStoreType
public init(store: AnimatableImageStoreType) {
self.store = store
}
...
}
public struct HomeView<
HomeViewStoreType: HomeViewStore
>: View {
@StateObject private var store: HomeViewStoreType
public init(store: HomeViewStoreType) {
self._store = StateObject(wrappedValue: store)
}
public var body: some View {
VStack {
Text(store.title)
Button {
store.buttonTapSubject.send(())
} label: {
Text("API Call")
}
.background(Color(.accent))
.padding()
Button {
store.retryTapSubject.send(())
} label: {
Text("Retry")
.font(.monserrat(.bold, 14))
}
.padding()
List(store.animatableImageStores) { animatableImageStore in
AnimatableImage(store: animatableImageStore)
}
}
.background(Color(.accent))
}
}
該代碼給了我以下錯誤訊息:

我的問題是,為什么 HomeViewStoreType.AnimatableImageStoreType 不符合 AnimatableImageStore 協議,而在 HomeViewStore 協議中我將其限制為 AnimatableImageStore 協議,而 Identifiable 哪個 AnimatableImageStore 符合?
如果有人能告訴我實作這一目標的正確方法,將不勝感激:)
uj5u.com熱心網友回復:
此行不限AnimatableImageStoreType于AnimatableImageStore:
associatedtype AnimatableImageStoreType = AnimatableImageStore
替換=為:,它將起作用:
associatedtype AnimatableImageStoreType: AnimatableImageStore
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483977.html
上一篇:如何將資料傳遞給最終視圖控制器
