Last active
April 19, 2021 13:01
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What get printed