How to copy objects in Swift?

I have the following class:

class Client {
  let name: String
  let age: Int

  init(name: String, age: Int) {
    self.name = name
    self.age = age
  }
}

let wrongClient = Client(name: "John", age: 9)

How to create a new version wrongClientwith the right age?

I need something like the following:

let rightClient = Client(wrongClient, age: 42)

For example, OCaml allows developers to do the following:

type client = {
  name : string;
  age : int;
}

let wrong_client = {name = "John"; age = 25}
let right_client = {wrong_client with age = 42}

Or in Scala:

case class Client(name: String, age: Int)

val wrongClient = Client(name: "John", age: 9)
val rightClient = wrongClient.copy(age=42)

EDIT

I want to experiment with data immutability and data exchange using Swift.

Because immutable data means “generating” values ​​from other values, “copying” objects can occur frequently. So my question is: how can I easily create new objects from other objects using Swift?

EDIT 2

I'm looking at Swiftz lenses right now .

+4
source share
5 answers

Client struct class, struct .

struct Client {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

var wrongClient = Client(name: "John", age: 18)
var rightClient = wrongClient
rightClient.age = 99

Client . age Client, Client 18.

+2

init.

   required init(name: String, age: Int) {
       self.name = name
       self.age = age
   }

   convenience init(from: Client, withAge: Int) {
       self.init(name: from.name, age: withAge)
   }
+1

There should be a better way, but my current solution is this:

   init(name: String, age: Int) {
       self.name = name
       self.age = age
   }

   init(from: Client, name: Int? = nill, age: Int? = nil) {
       self.name = name ?? Client.name
       self.age = age ?? Client.age
   }
+1
source

There is no definite short hand for this. I would recommend something like:

class Client {
    let name: String
    let age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    private init(from: Client, age:Int) {
        self.name = from.name
        self.age = age
    }

    func withAge(age:Int) -> Client {
        return Client(from: self, age: age)
    }
}

let right_client = Client(name: "John", age: 9)
let wrong_client = right_client.withAge(42)
0
source

If you need a copy of the array, just try with a filter and use something that is always true:

let oldTagValueKey = self.tagValueKey.filter({ $0.value.characters.isEmpty == false })
0
source

All Articles