ValueMaker.swift
import Foundation class ValueMaker: ObservableObject { @Published var value: Double = 0.0 private var timer = Timer() func start() { timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in self.value = Double.random(in: 0 ... 1) } } }
ContentView.swift
struct ContentView: View { @ObservedObject var maker = ValueMaker() var body: some View { VStack (alignment: .leading, spacing: 10){ Text("\(maker.value)") .font(.largeTitle) .foregroundColor((maker.value > 0.8) ? .white : .gray) .background((maker.value > 0.8) ? Color.red : Color.white) ZStack { Rectangle().stroke(.gray) Rectangle() .foregroundColor(.green) .scaleEffect(x:maker.value, y:1.0, anchor: .leading) } } .frame(width: 200, height: 80) .onAppear(perform: { maker.start() }) } }
Timer.scheduledTimerとして、Double.random(in: 0 … 1)で値を出力する
@ObservedObject var maker = ValueMaker() でValueMakerを呼び出している