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 Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.