Combine (6) : ObservableObject

Panther·2021년 4월 25일
0

Swift Combine Framework

목록 보기
6/7

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

"A type of object with a publisher that emits before the object has changed."

객체가 변화되기 전에 내보내는 publisher를 둔 객체의 타입입니다.

Declaration

protocol ObservableObject : AnyObject

Overview

ObservableObject@Published 프로퍼티의 변화가 있기 전에 변경된 값을 내보내는 objectWillChange 퍼블리셔를 합성합니다.

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)
cancellable = john.objectWillChange
    .sink { _ in
        print("\(john.age) will change")
}
print(john.haveBirthday())
// Prints "24 will change"
// Prints "25"

0개의 댓글