In the below example for stored property, where it should only update the value if it has changed. While setting the same value for the second time, willSet is skipping or returning, but didSet is still being printed. Any way we can block property update in willSet
?
Did Set value World
Message = World
Skip same value update World
Did Set value World
Message = World
If the value changes we should see Did Set value \(greeting)
else don't see this Did Set
message.
Did Set value World
Message = World
Skip same value update World
Message = World
var greeting = "Hello" {
willSet {
guard greeting != newValue else {
print("Skip same value update \(newValue)")
return
}
}
didSet {
print("Did Set value \(greeting)")
}
}
greeting = "World"
printGreeting()
greeting = "World"
printGreeting()
@MainActor func printGreeting() {
print("Message = \(greeting)")
}
I think a custom getter/setter will solve your problem and prevent a value from updating to the same value:
private var _greeting: String = "Hello"
var greeting: String {
get { _greeting }
set {
guard _greeting != newValue else {
print("Skip same value update \(newValue)")
return
}
_greeting = newValue
print("Did Set value \(newValue)")
}
}