[swift-evolution] "with" operator a la O'Caml?

Pierre Monod-Broca pierremonodbroca at gmail.com
Tue Dec 20 01:54:10 CST 2016


But for a struct to be immutable, you don't need all its properties to be let. (I guess that's Derrick's point)

´´´
struct Person { /* . . . var properties . . . */ }
let john = Person() // john is completely immutable
´´´

If a struct has var properties, you can do a mutable copy, change it, assign it to a new let, and you take advantage of immutability again.

´´´
let jim = { var copy = john
  copy.firstname = "Jim"
  return copy
}()

func with<T>(_ original: T, transform: (inout T) -> ()) -> T {
  var copy = original
  transform(&copy)
  return copy
}

let jane = with(john) { $0.firstname = "Jane" }
// jane is also immutable
´´´
(I didn't check this compiles)

Pierre

> Le 19 déc. 2016 à 23:08, Andy Chou via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> Value semantics help reduce the issues around mutability, but they don't go away completely. I would like to create structs that are completely immutable after construction. Turning the properties into vars unfortunately loses this idea.
> 
> The proposed 'with' function doesn't construct new instances, which means the let constants are already set. Nick's solution works, as it's basically a copy constructor that allows for changes while the new object is constructed. But it needs to be created for each struct. Which I'm fine with :)
> 
> Andy


More information about the swift-evolution mailing list