[Pitch] `With` functions in the standard library

Do these struct declare (even implicitly) a memberwise initializer? If they do, consider that you shouldn't use let properties with those.

You don't need to "copy and update" in Swift: when using structs, the language does it for you. Enforced value semantics is one of the foundational and most useful features in Swift, that makes it more powerful, in this regard, than many other languages.

And "mutable" structs is precisely where .with shines, because you can do something like this:

struct Person {
  var name: String
  var age: Int
}

// assuming that a certain `Person` instance already exists
let person = ...

// we can use `.with` to produce a new value in a safe way
let olderPerson = person.with { $0.age += 1 }

If the age property was a let, this wouldn't work, and you're be forced to write something like:

struct Person {
  let name: String
  let age: Int
}

// assuming that a certain `Person` instance already exists
let person = ...

// `.with` is useless
let olderPerson = Person(
  name: person.name,
  age: person.age + 1
)
2 Likes