Skip to content

Instantly share code, notes, and snippets.

@hannesoid
Created October 27, 2019 19:51
Show Gist options
  • Save hannesoid/5a34df8442fda03e14fa828a6113077b to your computer and use it in GitHub Desktop.
Save hannesoid/5a34df8442fda03e14fa828a6113077b to your computer and use it in GitHub Desktop.
Experiments with SwiftUI view initialization creation
import SwiftUI
final class SomeClass {
static var instanceNr: Int = 0
init(_ owner: String) {
SomeClass.instanceNr += 1
print("Created new instance (nr. \(SomeClass.instanceNr)) for owner \(owner)")
}
}
struct ContentView: View {
let someClass = SomeClass("mainView")
@State var counter: Int = 0
var body: some View {
VStack {
Button(action: { // tapping this button recreates SubView and with it subSomeInstance
self.counter += 1
}) {
Text("Main counter \(counter)")
}
SubView()
Text("Instances of SomeClass \(SomeClass.instanceNr)")
}
}
}
struct SubView: View {
private let subSomeInstance = SomeClass("subview")
@State private var counter: Int = 0
var body: some View {
Button(action: { // tapping this button doesn't recreate subSomeInstance
self.counter += 1
}) {
Text("Sub counter \(counter)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment