Assign if different

One case where I've wanted to do something like this was when using Core Data. Assigning any value to a modeled property, even if it's the same value, results in the object being marked "dirty", and thus means that it will be included in the next save transaction. That results in more I/O traffic and higher memory usage, so we try to avoid re-assigning an equal value when possible.

I've written this helper, and it works well for me:

extension NSManagedObject {
    public func updateIfNotEqual<T: Equatable>(
        _ path: ReferenceWritableKeyPath<Self, T>, 
        _ newValue: T) 
    {
        if self[keyPath: path] != newValue {
            self[keyPath: path] = newValue
        }
    }
}

// Used like this:
person.updateIfNotEqual(\.name, updatedName)
6 Likes