Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Last active September 22, 2022 09:39
Show Gist options
  • Save Koshimizu-Takehito/32e5df4b08b2561a1319b2b6a930d932 to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/32e5df4b08b2561a1319b2b6a930d932 to your computer and use it in GitHub Desktop.
StateObject(wrappedValue:) を直接呼び出すと余計なオブジェクトを作る
import SwiftUI
// MARK: - ObservableObject
final class Counter: ObservableObject {
@Published private(set) var count: Int
deinit {
print("🍂", #function, count)
}
init(count: Int = 1) {
self.count = count
print("🌱", #function, count)
}
func increment() {
count += 1
}
func reset() {
count = 1
}
}
// MARK: - View
struct ContentView: View {
var body: some View {
FooView()
}
}
struct FooView: View {
@StateObject var counter = Counter()
var body: some View {
VStack(spacing: 16) {
HStack {
ForEach(0..<counter.count, id: \.self) { offset in
BarView(counter: Counter(count: offset+1))
}
}
Button("Increment") { counter.increment() }
Button("Reset") { counter.reset() }
}
}
}
struct BarView: View {
@StateObject var counter: Counter
// // ⛔️ 余計なオブジェクトを作る
// init(counter: Counter) {
// _counter = StateObject(wrappedValue: counter)
// }
// // 🤓 余計なオブジェクトはつくらない。リファレンスでは直接よぶべきではないとしているので利用は避けたほうがよいかも?💭
// // https://developer.apple.com/documentation/swiftui/stateobject/init(wrappedvalue:)
// init(counter: @escaping @autoclosure () -> Counter) {
// _counter = StateObject(wrappedValue: counter())
// }
var body: some View {
Text(counter.count.formatted())
.foregroundColor(.mint)
}
}
// MARK: - PreviewProvider
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