struct Person {<br> Var name: String = ""<br><br>func with(name n: String) -> Person {<br>var a = self <br><a href="http://a.name">a.name</a> = name<br>return a<br>}<br>}<br><br>let andy = Person().with(name: "Andy")<br>let brandon = andy.with(name: "Brandon")<br><div class="gmail_quote"><div dir="ltr">On Mon, Dec 19, 2016 at 10:28 AM Andy Chou via swift-evolution <<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">I like that structs are value types in Swift, this encourages the use of immutable data. O'Caml has an operator "with" that allows for copying an existing struct with a change to one field. I looked at Lenses for this functionality and it seems like a lot to digest for something so simple. I also tried to implement this using a constructor, or a function, and it was not obvious how to do so without a lot of code duplication.<br class="gmail_msg">
<br class="gmail_msg">
What's I'm looking for is something like this (not necessarily with this syntax):<br class="gmail_msg">
<br class="gmail_msg">
struct Person {<br class="gmail_msg">
let name: String<br class="gmail_msg">
let address: String<br class="gmail_msg">
let phone: String<br class="gmail_msg">
}<br class="gmail_msg">
<br class="gmail_msg">
func f() {<br class="gmail_msg">
let andy = Person(name: "Andy", address: "1 Battery St., San Francisco, CA", phone: "1234567")<br class="gmail_msg">
let chris = andy.with(name: "Chris")<br class="gmail_msg">
let dave = andy.with(address: "50 Townsend St., San Francisco, CA")<br class="gmail_msg">
}<br class="gmail_msg">
<br class="gmail_msg">
I tried to implement a "with" function like this but default arguments cannot reference properties of self. Same problem trying to do this in a constructor.<br class="gmail_msg">
<br class="gmail_msg">
Obviously it's possible to create an entirely new Person specifying the values from an existing Person, but this is very tedious with structures with many properties.<br class="gmail_msg">
<br class="gmail_msg">
Anyone taken a look at this before? Any suggestions?<br class="gmail_msg">
<br class="gmail_msg">
Andy<br class="gmail_msg">
<br class="gmail_msg">
_______________________________________________<br class="gmail_msg">
swift-evolution mailing list<br class="gmail_msg">
<a href="mailto:swift-evolution@swift.org" class="gmail_msg" target="_blank">swift-evolution@swift.org</a><br class="gmail_msg">
<a href="https://lists.swift.org/mailman/listinfo/swift-evolution" rel="noreferrer" class="gmail_msg" target="_blank">https://lists.swift.org/mailman/listinfo/swift-evolution</a><br class="gmail_msg">
</blockquote></div>