我创建了 3 个不同视图模型的实例,并将每个视图模型分配给一个状态对象。我如何将其放入调度队列?

I create an instance of 3 different view models and assign each to a state object. How do I place this into a dispatch queue?

我有一个 Swift 程序可以正常工作。我有 3 个视图模型,每个视图模型都调用一个单独的模型。每个模型调用一个函数来读取一个单独的大型 CSV 文件,执行一些操作和 returns 一个数据框。这需要一些时间,我想加快速度。

Swift 提供了一个 DispatchQueue 允许将代码放入具有 QOS 的异步全局队列中,我相信如果我 运行 以这种方式创建视图模型,我会尽快显示初始视图。

问题是:我不知道如何合并它。任何帮助我指明正确方向的帮助将不胜感激。

下面是我的内容视图、一个视图模型和一个模型。最后的测试调度队列代码在操场上运行成功。

struct ContentView: View {
    @StateObject var vooVM: VOOViewModel = VOOViewModel()
    @StateObject var vfiaxVM: VFIAXViewModel = VFIAXViewModel()
    @StateObject var principalVM: PrincipalViewModel = PrincipalViewModel()
    @State private var selectedItemId: Int?
    var body: some View {
        NavigationView {
            VStack (alignment: .leading) {
                List {
                    Spacer()
                        .frame(height: 20)
                    Group {
                        Divider()
                        NavigationLink(destination: Summary(vooVM: vooVM, vfiaxVM: vfiaxVM, prinVM: principalVM), tag: 1, selection: $selectedItemId, label: {
                            HStack {
                                Image(systemName: "house")
                                    .padding(.leading, 10)
                                    .padding(.trailing, 0)
                                    .padding(.bottom, 5)
                                Text("Summary")
                                    .bold()
                                    .padding(.bottom, 2)
                            } // end h stack
                        })
                    } // end group
                    NavigationLinks(listText: "VOO", dataFrame1: vooVM.timeSeriesDailyDF1, dataFrame5: vooVM.timeSeriesDailyDF5)
                    NavigationLinks(listText: "VFIAX", dataFrame1: vfiaxVM.timeSeriesDailyDF1, dataFrame5: vfiaxVM.timeSeriesDailyDF5)
                    NavigationLinks(listText: "Principal", dataFrame1: principalVM.timeSeriesDailyDF1, dataFrame5: principalVM.timeSeriesDailyDF5)
                    Divider()
                    Spacer()
                } // end list
            } // end  v stack
        } // end navigation view
        .onAppear {self.selectedItemId = 1}
        .navigationTitle("Stock Data")
        .frame(width: 1200, height: 900, alignment: .center)
    } // end body view
} // end content view

查看模型

class VOOViewModel: ObservableObject {
    @Published private var vooModel: VOOModel = VOOModel()
    var timeSeriesDailyDF1: DataFrame {
        return vooModel.vooDF.0
    }
    var timeSeriesDailyDF5: DataFrame {
        return vooModel.vooDF.1
    }
    var symbol: String {
        return vooModel.symbol
    }
    var currentShares: Double {
        return vooModel.currentShares
    }
    var currentSharePrice: Double {
        let lastRowIndex: Int = vooModel.vooDF.0.shape.rows - 1
        let currentPrice: Double = (vooModel.vooDF.0[row: lastRowIndex])[1] as! Double
        
        return currentPrice
    }
    var percentGain: Double {
        let pastValue: Double = (vooModel.vooDF.0[row: 0])[1] as! Double
        let numRows: Int = vooModel.vooDF.0.shape.rows - 1
        let curValue: Double = (vooModel.vooDF.0[row: numRows])[1] as! Double
        let oneYearGain: Double = (100 * (curValue - pastValue)) / pastValue
        return oneYearGain
    }
}

型号

struct VOOModel {
    var vooDF = GetDF(fileName: "FormattedVOO")
    let symbol: String = "VOO"
    let currentShares: Double = 1
}

游乐场代码

let myQue = DispatchQueue.global()
let myGroup = DispatchGroup()
myQue.async(group: myGroup) {
    sleep(5)
    print("Task 1 complete")
}
myQue.async(group: myGroup) {
    sleep(3)
    print("Task 2 complete")
}
myGroup.wait()
print("All tasks completed")

我只使用了 1 个 viewmodel 而不是 3 个 viewmodel 就解决了我的问题。viewmodel 调用了所有三个经过修改的模型,以便它们读取 CSV 文件并将其放入数据框中的函数调用包含在功能。该函数又在视图模型中的函数中调用,该函数在视图模型初始化中调用。下面是更新后的代码。请注意,已简化 ContentView 以简化测试。

新内容视图:

struct ContentView: View {
    @StateObject var viewModel: ViewModel = ViewModel()
    var body: some View {
        let printValue1 = (viewModel.dataFrames.0.0[row: 0])[0]
        let tempValue = (viewModel.dataFrames.0.0[row: 0])[1] as! Double
        let tempValueFormatted: String = String(format: "$%.2f", tempValue)
        Text("\(dateToStringFormatter.string(from: printValue1 as! Date))" + "     " + tempValueFormatted )
            .frame(width: 1200, height: 900, alignment: .center)
    }
} 

新视图模型:

class ViewModel: ObservableObject {
    @Published private var vooModel: VOOModel = VOOModel()
    @Published private var vfiaxModel: VFIAXModel = VFIAXModel()
    @Published private var principalModel: PrincipalModel = PrincipalModel()
    var dataFrames = ((DataFrame(), DataFrame()), (DataFrame(), DataFrame()), (DataFrame(), DataFrame()))
    init() {
        self.dataFrames = GetDataFrames()
    }
    func GetDataFrames() -> ((DataFrame, DataFrame), (DataFrame, DataFrame), (DataFrame, DataFrame)) {
        let myQue: DispatchQueue = DispatchQueue.global()
        let myGroup: DispatchGroup = DispatchGroup()
        var vooDF = (DataFrame(), DataFrame())
        var vfiaxDF = (DataFrame(), DataFrame())
        var principalDF = (DataFrame(), DataFrame())
        myQue.async(group: myGroup) {
            vfiaxDF = self.vfiaxModel.GetData()
        }
        myQue.async(group: myGroup) {
            principalDF = self.principalModel.GetData()
        }
        myQue.async(group: myGroup) {
            vooDF = self.vooModel.GetData()
        }
        myGroup.wait()
        return (vooDF, vfiaxDF, principalDF)
    } 
}

新机型之一。除了他们读取的 CSV 文件外,其他 2 个完全相同。

struct VOOModel {
    let symbol: String = "VOO"
    let currentShares: Double = 1
    func GetData() -> (DataFrame, DataFrame) {
        let vooDF = GetDF(fileName: "FormattedVOO")
        return vooDF
    }
}