I want to perform some actions when any property value gets changed in the model.
struct RoomDataModel: Equatable{
var selectedLocationName : String = ""
var selectedRoomName : String = ""
var selectedRoomImage : String = ""
var roomId: String = ""
static func == (lhs: RoomDataModel, rhs: RoomDataModel) -> Bool {
return lhs.selectedRoomName == rhs.selectedRoomName && lhs.selectedRoomImage == rhs.selectedRoomImage
}
}
How I used room object in View :
@State var roomDetail = RoomDataModel()
var body: some View {
someview
.onChange(of: roomDetail) { newValue in
//performing some action here
}
}
I have the above model which triggers onChange()
when selectedRoomName
and selectedRoomImage
both values changed. but I want to trigger onChange
even if there is a change in any one of the property values. If I change only selectedRoomImage
then onChange()
is not getting triggered.
I am new to SwiftUI and Equatable protocol. I would greatly appreciate any help.
Thanks.
2
Answers
The
onChange
method is not being triggered when onlyselectedRoomImage
is changed because theEquatable
protocol’s==
function is only checking for equality between theselectedRoomName
andselectedRoomImage
properties of the two instances being compared.To trigger the
onChange
method when any one of the property values changes, you can modify the == function to check for equality between all the properties of the two instances being compared. Here’s an example:Try this approach, removing the
static func == ...
fromRoomDataModel
.Here is the example code that shows it works: