【发布时间】:2019-06-30 09:50:05
【问题描述】:
我正在使用 SwiftUI 并想抽象一个 @EnvironmentObject。目标是从生产 BindableObject 切换到假的(测试/在本地工作......)
首先我刚刚声明了一个协议:
protocol FetcherInterface: BindableObject {
associatedtype T
var didChange: PassthroughSubject<[T], Never> { get set }
var values: [T] { get set }
}
那我就可以写一个符合FetcherInterface的网络根类了:
open class NetworkFetcher<T: Decodable>: FetcherInterface {
public var didChange = PassthroughSubject<[T], Never>()
internal var values: [T] = [T]() {
didSet {
DispatchQueue.main.async {
dump("did set network values \(self.values)")
self.didChange.send(self.values)
}
}
}
internal func loadAsync(values: [T]) {
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
self.values = values
}
}
}
我现在可以有一个像这样的子类:
final class PlacesNetworkFetcher: NetworkFetcher<Place>, PlacesQueryInterface {
func loadPlacesFromCountryCode(_ countryCode: String) {
self.loadAsync(values: [Place(id: UUID(), name: "London")])
}
}
PlacesQueryInterface:
protocol PlacesQueryInterface {
func loadPlacesFromCountryCode(_ countryCode: String)
}
extension PlacesQueryInterface where Self: FetcherInterface {}
当我想在我的ContentView.swift 中使用所有这些时,Xcode 永远不会结束编译。
看起来环境对象导致了这个:
@EnvironmentObject var placesQueryInterface: PlacesQueryInterface
你知道为什么吗?
编辑:如果你想测试,我放了project skeleton
【问题讨论】:
-
在我的机器上,它甚至从未完成索引。显然这使编译器/索引器非常不高兴。请立即向 Apple 提交错误报告。
-
感谢@matt 我刚刚做到了。
-
您找到解决方案了吗?我想将它应用到同一个案例(测试/工作)