[swift-evolution] idea: immutable setters for structs and tuples?

Erica Sadun erica at ericasadun.com
Thu Mar 24 14:12:39 CDT 2016


> On Mar 23, 2016, at 3:32 AM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> let john = {firstName="John"; lastName="Doe"}
>> let alice = {john with FirstName="Alice"}
>> 
>>  Current way to do this in Swift is:
>> 
>> let john = (firstName:"John", lastName:"Doe")
>> var alice = john
>> alice.firstName = "Alice"
> 
> I think this is better modeled in Swift as something like:
> 
> 	let john = (firstName:"John", lastName:"Doe")
> 	let alice = with(john) {
> 		$0.firstName = "Alice"
> 	}

You can kind of do this now:

struct Person {
    var firstName, lastName: String
}

func modify<T>(item: T, update: (inout T) -> Void) -> T {
    var this = item
    update(&this)
    return this
}

let carol: Person = modify(john) {
    $0.firstName = "Carol"
}

print(carol)


-- E
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160324/d7ba265d/attachment.html>


More information about the swift-evolution mailing list