"Discover Observation in SwiftUI" session has a bug

They provide an example on using @Observable in minute 5:14 :

@Observable class Account { var userName: String? }

However, if you put that in Xcode this gives an error: @Observable requires property 'userName' to have an initial value (from macro 'Observable')

Anyone else seeing this?

Post not yet marked as solved Up vote post of ericagredo Down vote post of ericagredo
983 views

Replies

Yes, I'm seeing this too.

var timer: AnyCancellable? is throwing the same error:

@Observable requires property 'timer' to have an initial value (from macro 'Observable')

EDIT: In my case making the timer: AnyCancellable? = nil removes the error

Here's my code:

@Observable class SubscriberViewModel {
    
    public var count: Int = 0
    var timer: AnyCancellable?
    
    func setupTimer() {
        timer = Timer
            .publish(every: 1, on: .main, in: .common)
            .autoconnect()
            .sink { [weak self] _ in
                self?.count += 1
            }
    }
}

Does it help to do var userName: String? = nil?

Does it help to do [initialise it to] nil?

Yep. This is more fallout from the issued discussed in this thread.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"