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

Brent Royal-Gordon brent at architechies.com
Wed Mar 23 04:32:33 CDT 2016


> 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"
	}

`with` would be something like:

	func with<Value>(value: Value, function: Value throws -> Void) rethrows -> Value {
		var mutableValue = value
		return try function(&mutableValue)
	}

This would serve many different purposes:

* If the value is a value type, allows you to return a modified copy
* Allows you to customize a value's properties immediately after initializing it, which many people have asked for
* Acts as a `tap` function when the block doesn't change the value (see <http://ruby-doc.org/core-2.3.0/Object.html#method-i-tap>)

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list