Skip to content

Instantly share code, notes, and snippets.

@auramagi
Created June 29, 2022 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save auramagi/4a810e2c64b1be04a40e0c2d775a3529 to your computer and use it in GitHub Desktop.
Save auramagi/4a810e2c64b1be04a40e0c2d775a3529 to your computer and use it in GitHub Desktop.
Manual testing code for `@StateObject` backport
import Combine
import SwiftUI
import SwiftUIBackports
@main
struct BackportTestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
final class Model: ObservableObject {
let id: String
@Published var i = 0
private var cancellables: Set<AnyCancellable> = []
init(id: String) {
self.id = id
print("Model", id, #function)
Timer.publish(every: 1, on: .main, in: .common)
.autoconnect()
.sink { [weak self] _ in self?.i += 1 }
.store(in: &cancellables)
}
deinit {
print("Model", id, #function)
}
}
struct ContentView: View {
@State var i = 0
var body: some View {
VStack(spacing: 16) {
if #available(iOS 14.0, *) {
StateObjectView(model: Model(id: "StateObject")).border(Color.accentColor)
} else {
// Fallback on earlier versions
}
ObservableObjectView(model: Model(id: "ObservableObject")).border(Color.accentColor)
StateObjectBackportView(model: Model(id: "Backport.StateObject")).border(Color.accentColor)
Button {
i += 1
} label: {
Text("i \(i.description)")
}
}
}
}
@available(iOS 14.0, *)
struct StateObjectView: View {
@StateObject var model: Model
var body: some View {
VStack {
Text("\(model.id) \(model.i.description)")
BindingView(i: $model.i)
}
}
}
struct ObservableObjectView: View {
@ObservedObject var model: Model
var body: some View {
VStack {
Text("\(model.id) \(model.i.description)")
BindingView(i: $model.i)
}
}
}
struct StateObjectBackportView: View {
@Backport.StateObject var model: Model
var body: some View {
VStack {
Text("\(model.id) \(model.i.description)")
BindingView(i: $model.i)
}
}
}
struct BindingView: View {
@Binding var i: Int
var body: some View {
Text("Binding \(i.description)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment