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

Rien Rien at Balancingrock.nl
Mon Dec 19 13:25:07 CST 2016


A little more work, but I like this pattern.

struct Person {
    
    let name: String
    let address: String
    let phone: String
    
    func name(_ n: String) -> Person {
        return Person(name: n, address: self.address, phone: self.phone)
    }
    
    func address(_ a: String) -> Person {
        return Person(name: self.name, address: a, phone: self.phone)
    }

    func phone(_ p: String) -> Person {
        return Person(name: self.name, address: self.address, phone: p)
    }
}

let p1 = Person(name: "Andrew", address: "Milkyway", phone: "031234")

let p2 = p1.name("Bart")

let p3 = p2.name("Jack").address("Earth”)

Regards,
Rien

Site: http://balancingrock.nl
Blog: http://swiftrien.blogspot.com
Github: http://github.com/Swiftrien
Project: http://swiftfire.nl




> On 18 Dec 2016, at 02:40, Andy Chou via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 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.
> 
> What's I'm looking for is something like this (not necessarily with this syntax):
> 
> struct Person {
>    let name: String
>    let address: String
>    let phone: String
> }
> 
> func f() {
>    let andy = Person(name: "Andy", address: "1 Battery St., San Francisco, CA", phone: "1234567")
>    let chris = andy.with(name: "Chris")
>    let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
> }
> 
> 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.
> 
> 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.
> 
> Anyone taken a look at this before? Any suggestions?
> 
> Andy
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list