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

Can a class change one property when another is updated externally?

Forums > SwiftUI

Hello. I have a class that contains, among other things, a date, and a fillColor that changes based how far back in time the date is from now. I use the class's init to set the initial fillColor based on the date and that works fine. However, that only works during object instantiation. In the UI when the user adds a new object, today's date is passed in, so the same color is always displayed.

What I'd like to be able to do is, when the object's date is changed in a view through it's binding, I'd like that to trigger a re-evaluation of the object's fillColor, adjusting it based on the same logic used during init.

I've thought about a didSet property observer on patchDate, but it doesn't work. The date does change when updated through a standard datepicker, but the color never changes from it's initial value.

I can do the time calculations in the view that the user changes the date in, but I'd rather let the class take care of that.

@Model
class Demo {
    var patchDate: Date {
        didSet {
            self.fillColor = .gray   // testing if this code is ever reached. It isn't?
        }
    }
    var fillColor: String 

    init( patchdate: Date, fillColor: String) { 
        self.patchDate = .patchDate
        self.fillColor = {
            switch patchDate {
                case ...Date(timeIntervalSinceNow: TimeInterval(60 * 60 * 24 * -60): .red
                case ...Date(timeIntervalSinceNow: TimeInterval(60 * 60 * 24 * -30): .yellow
                default: .green
            }
        }
    }
}

Am I going down the wrong road on this? TIA!

   

This is the same question ask on Slack https: // hackingwithswift .slack . com/archives/C012XAR7XUM/p1736925817073859

   

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.