[swift-evolution] idea: immutable setters for structs and tuples?
Maximilian Hünenberger
m.huenenberger at me.com
Wed Mar 23 04:08:08 CDT 2016
I cannot remember any use of such a feature but instead of a language feature there is also a reasonable library solution:
// inspired by the lens idea (of Joe Groff I think)
// there is probably a better name
func lens<T>(value: T, lensClosure: inout T -> ()) -> T {
var value = value
lensClosure(&value)
return value
}
// usage
let john = (firstName:"John", lastName:"Doe")
let alice = lens(john) { $0.firstName = "Alice" }
Kind regards
- Maximilian
> Am 23.03.2016 um 09:06 schrieb Zsolt Szatmári via swift-evolution <swift-evolution at swift.org>:
>
> Dear All,
>
> The only thing I am really missing right now from Swift is described as following. This works in some other languages, e.g. F#, Kotlin, and Haskell.
>
> F# example (taken from https://fsharpforfunandprofit.com/posts/correctness-immutability/)
>
> 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"
>
> This might seem to be a nuance, but it's more cumbersome (especially if one wants to do this frequently), and we are left with a var at the end.
> Also, this idea rhymes with the current direction of removing var arguments from functions.
> What do You think? Thank You.
>
> Zsolt
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160323/84984d21/attachment.html>
More information about the swift-evolution
mailing list