Skip to content

Instantly share code, notes, and snippets.

@treastrain
Created July 3, 2023 04:06
Show Gist options
  • Save treastrain/b6990892af52f32b245fc78ffad96564 to your computer and use it in GitHub Desktop.
Save treastrain/b6990892af52f32b245fc78ffad96564 to your computer and use it in GitHub Desktop.
Swift・SwiftUI・Combine・ObservableObject チャレンジ このコード例の場合、「object1 will change」・「object2 will change」・「object3 will change」はそれぞれそれぞれ何回 print されるか?
import Combine
import Foundation
// MARK: - パターン1
final class Object1: ObservableObject {
@Published var value1 = 0
@Published var value2 = 0
@Published var value3 = 0
}
// MARK: - パターン2
struct Properties2 {
var value1 = 0
var value2 = 0
var value3 = 0
}
final class Object2: ObservableObject {
@Published var properties = Properties2()
}
// MARK: - パターン3
struct Properties3 {
let value1: Int
let value2: Int
let value3: Int
}
final class Object3: ObservableObject {
@Published var properties = Properties3(value1: 0, value2: 0, value3: 0)
}
// MARK: - 実行
let object1 = Object1()
let object2 = Object2()
let object3 = Object3()
let cancellable1 = object1.objectWillChange
.sink { _ in
print("object1 will change")
}
let cancellable2 = object2.objectWillChange
.sink { _ in
print("object2 will change")
}
let cancellable3 = object3.objectWillChange
.sink { _ in
print("object3 will change")
}
object1.value1 = 1
object1.value2 = 2
object1.value3 = 3
object2.properties.value1 = 1
object2.properties.value2 = 2
object2.properties.value3 = 3
object3.properties = .init(value1: 1, value2: 2, value3: 3)
// Q. "object1 will change"・"object2 will change"・"object3 will change" は
// それぞれ何回 print されるか?
RunLoop.current.run()
@treastrain
Copy link
Author

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