Skip to content

Instantly share code, notes, and snippets.

@kean
Last active Apr 19, 2021
Embed
What would you like to do?
// Version 1: Using initializer directly
struct ContentView: View {
@State var count = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("container: \(count)")
.padding()
.onReceive(timer) { _ in
self.count += 1
}
Subview(count)
}
}
}
struct Subview: View {
@StateObject var foo: Foo
init(_ count: Int) {
_foo = StateObject(wrappedValue: Foo(count))
print("init subview \(count)")
}
var body: some View {
Text("subview: \(foo.count)")
}
}
final class Foo: ObservableObject {
let count: Int
init(_ count: Int) {
self.count = count
print("init foo \(count)")
}
deinit {
print("deinit foo \(count)")
}
}
// Version 2: Using generated initializer
struct ContentView: View {
@State var count = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("container: \(count)")
.padding()
.onReceive(timer) { _ in
self.count += 1
}
Subview(foo: Foo(count))
}
}
}
struct Subview: View {
@StateObject var foo: Foo
var body: some View {
Text("subview: \(foo.count)")
}
}
final class Foo: ObservableObject {
let count: Int
init(_ count: Int) {
self.count = count
print("init foo \(count)")
}
deinit {
print("deinit foo \(count)")
}
}
@kean
Copy link
Author

kean commented Dec 28, 2020

What get printed

init subview 0
init foo 0
init subview 1
init subview 2
init subview 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment