The following code works and assigns the topLeftGameState
to a timer. If the globalGameState
changes to running
, the topLeftGameState
changes accordingly.
@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)
So this code looks really ugly and I would like to write a function for all the @Published
variables:
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)
}
This throw an error: Cannot infer contextual base in reference to member 'ready'
I do not know how to get the appropriate value from the publisher? Does anyone have any advice for me?
Edit:
How can I write a function and pass @Published
variables?