GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Why are computed properties allow to be published in iOS 17?

Forums > SwiftUI

Before iOS 17, this code does not compile:

class AuthManager: ObservableObject {
    @Published var accessToken: String?
    @Published var refreshToken: String?
    @Published var isAuthenticated: Bool { // NOT ALLOWED TO BE PUBLISHED
        return accessToken != nil && refreshToken != nil
    }
    // initializers
}

Following the migration guide from Apple, which suggests to basically replace ObservableObject with Observable and remove all the @Published property wrappers. And afterwards the follow now compiles:

@Observable
class AuthManager {
    var accessToken: String?
    var refreshToken: String?
    var isAuthenticated: Bool {
        return accessToken != nil && refreshToken != nil
    }
}

And I can indeed use isAuthenticated as a published state variable. So how come? Since it's computed, how would SwiftUI determine whether if it's changed? And would this still work if the computation was non-trivial? e.g. computed using the result of an http request

   

they have different implementations under the hood presumably the old way just didnt handle this for technical reasons, limitations in combine perhaps

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.