Home > AI > Uncategorized

ObservableObject

Source: https://developer.apple.com/documentation/combine/observableobject


import Foundation
import SwiftUI


class Contact: ObservableObject {
    @Published var name: String
    @Published var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func haveBirthday() -> Int {
        age += 1
        return age
    }
}

let john = Contact(name: "John Appleseed", age: 24)
// fired before the value changed
var cancellable = john.objectWillChange
    .sink { _ in
        print("\(john.age) will change")
}

print(john.haveBirthday())
// Prints "24 will change"
// Prints "25"

Execute on terminal

>> touch a.swift
>> swift a.swift
Related posts:

Leave a Reply