Created
July 3, 2023 04:06
-
-
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 されるか?
This file contains 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
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() |
Author
treastrain
commented
Jul 3, 2023
- Twitter: https://twitter.com/treastrain/status/1675717733923827712
- Fediverse (e.g. Mastodon, Misskey): https://misskey.io/notes/9gpwov0qq5
- Bluesky: https://bsky.app/profile/treastrain.jp/post/3jzlpff3tuf2y
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment