Swift - copy only non-nil properties from one Struct to another

Viewed 54

I am trying to copy the values JSON decoded Firebase RemoteConfig's new values struct to another local instance same type. Obviously it replaces all old values from new object, but I want to replace only properties that have non-nil, so the local property will preserve their default values.

eg:

struct Config {
    let port: Int
    let details: String?
}

var localConfig = Config(port: 80, details: "Default configuration")
var remoteConfig = Config(port: 100, details: nil)

/// Here I want to copy only those properties are not nil
/// otherwise leave its default value
localConfig = remoteConfig

print (localConfig)
print (remoteConfig)

Obviously I can check each property for nil and assign individually but its not easy if the structure if huge and complex. I just wanted to know if there any standard option in Swift to achieve this.

1 Answers

How about:

struct Config {
var port: Int
var details: String?

 mutating func patch(with remote: Config){
    self.port = remote.port
    self.details = remote.details ?? self.details
 }
}

Usage:

var local = Config(port: 2, details: "myDetail")
var remote = Config(port: 3, details: nil)

local.patch(with: remote)
Related