Skip to content

Instantly share code, notes, and snippets.

@webuniverseio
Created July 20, 2022 20:29
Show Gist options
  • Save webuniverseio/0f3b7975f28427ebace67ea9cf3304bd to your computer and use it in GitHub Desktop.
Save webuniverseio/0f3b7975f28427ebace67ea9cf3304bd to your computer and use it in GitHub Desktop.
EggTimer MVC iOS project
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var bar: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
bar.alpha = 0
}
@IBAction func onChoiceSelected(_ sender: UIButton) {
if let currentTitle = sender.currentTitle, let eggTimer = MainModel.msTimers.first(where: { x in x.name == currentTitle }) {
bar.progress = 0
bar.alpha = 1
let model = MainModel(
eggTimer.msTime / 1000,
onIncrement: { (progress: Float) in self.bar.progress = progress},
onFinish: {self.bar.alpha = 0}
)
model.startTimer()
}
}
}
import Foundation
struct EggTimer {
let name: String
let msTime: Float
init(_ name: String, _ seconds: Int) {
self.name = name
msTime = Float(seconds) * 1000
}
}
import Foundation
var timer = Timer()
func clearTimer() {
timer.invalidate()
}
struct MainModel {
static let msTimers = [
EggTimer("Soft", 5),
EggTimer("Medium", 8),
EggTimer("Hard", 12)
]
var seconds: Float = 0
let initialValue: Float
typealias IncrementCallback = (_ progress: Float) -> Void
typealias FinishCallback = () -> Void
let onIncrement: IncrementCallback
let onFinish: FinishCallback
// why need @escaping
init (_ initialValue: Float, onIncrement: @escaping IncrementCallback, onFinish: @escaping FinishCallback) {
clearTimer()
self.initialValue = initialValue
self.onIncrement = onIncrement
self.onFinish = onFinish
}
func startTimer() {
//why need to capture self?
var this = self
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in this.onTimerUpdate() }
}
private mutating func onTimerUpdate() {
if seconds < initialValue {
seconds += 1
onIncrement(seconds / initialValue)
} else {
onFinish()
clearTimer()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment