SwiftUI:如何将@Published变量传递给函数参数并获取值

问题描述

以下代码有效,并将topLeftGameState分配给计时器。如果globalGameState更改为running,则topLeftGameState也会相应更改。

@Published var topLeftGameState: GameState = .notReady
@Published var topRightGameState: GameState = .notReady
@Published var bottomLeftGameState: GameState = .notReady

private let timerPublisher = Timer.publish(every: 0.01,on: .main,in: .common)    
// ...
 timerPublisher.autoconnect().sink(receiveValue: { currentDate in
        switch self.globalGameState {
        case .running(startDate: let startDate):
            let elapsedtime = currentDate - startDate
            if self.topLeftGameState == .ready { //,{
                self.topLeftGameState = .running(elapsedtime: elapsedtime.timeInterval)
            }
            if case .running(elapsedtime: _) = self.topLeftGameState {
                self.topLeftGameState = .running(elapsedtime: elapsedtime.timeInterval)
            }
            
            if self.topRightGameState == .ready { //,{
                self.topRightGameState = .running(elapsedtime: elapsedtime.timeInterval)
            }
            if case .running(elapsedtime: _) = self.topRightGameState {
                self.topRightGameState = .running(elapsedtime: elapsedtime.timeInterval)
            }
            
            if self.bottomLeftGameState == .ready { //,{
                self.bottomLeftGameState = .running(elapsedtime: elapsedtime.timeInterval)
            }
            if case .running(elapsedtime: _) = self.bottomLeftGameState {
                self.bottomLeftGameState = .running(elapsedtime: elapsedtime.timeInterval)
            }
        default: ()
        }
    }).store(in: &cancellables)

所以这段代码看起来非常丑陋,我想为所有@Published变量写一个函数

    addTimePublisher(for: topLeftGameState)
    addTimePublisher(for: topRightGameState)
        //...
    private func addTimePublisher(for gameState: Published<GameState>.Publisher) {
        timerPublisher.autoconnect().sink(receiveValue: { currentDate in
            switch self.globalGameState {
            case .running(startDate: let startDate):
                let elapsedtime = currentDate - startDate
                if self.gameState == .ready {
                    self.gameState = .running(elapsedtime: elapsedtime.timeInterval)
                }
                if case .running(elapsedtime: _) = self.gameState {
                    self.gameState = .running(elapsedtime: elapsedtime.timeInterval)
                }
                
            default: ()
            }
            print(currentDate)
        }).store(in: &cancellables)
    }

这将引发错误Cannot infer contextual base in reference to member 'ready'

我不知道如何从发行商那里获得适当的价值? 有人对我有什么建议吗?

编辑: 如何编写函数并传递@Published变量?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)