Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created October 7, 2024 13:23
Show Gist options
  • Save christianselig/797fc7b773e5f7b4ce454543242cd1ed to your computer and use it in GitHub Desktop.
Save christianselig/797fc7b773e5f7b4ce454543242cd1ed to your computer and use it in GitHub Desktop.
Attempting to observe pesky disk cats in SwiftUI
import SwiftUI
struct ContentView: View {
@State var catWorld = CatWorld.shared
var body: some View {
VStack {
Text("Value: \(catWorld.giveCat() ?? "No cat yet")")
Text("num: \(catWorld.number)")
// Button is just for sake of example, in reality pretend an external event changes CatWorld
Button {
catWorld.saveCat(value: Int.random(in: 0...999))
} label: {
Text("Randomize")
}
}
}
}
@Observable
class CatWorld {
static let shared = CatWorld()
// I could do this, but I want people to go through the function accessors:
// var cat: String?
// I could also do this, where I just change a random number/ID whenever the disk store changes, but I'd need to invisibly add this to the UI, which feels hacky?
// var number: Int = 5
private let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("cat.txt")
func giveCat() -> String? {
return try? String(contentsOf: url, encoding: .utf8)
}
func saveCat(value: Int) {
// This does not work 🥲
SwiftUI.magicallyEmitThatThisInstanceChanged()
// Hacky:
// number = Int.random(in: 0...999999999)
try! "cat\(value)".write(to: url, atomically: true, encoding: .utf8)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment