Skip to content

Instantly share code, notes, and snippets.

@RoyalIcing
Last active April 22, 2016 08:09
Show Gist options
  • Save RoyalIcing/ba2ce9dfd49595dacce07394de579172 to your computer and use it in GitHub Desktop.
Save RoyalIcing/ba2ce9dfd49595dacce07394de579172 to your computer and use it in GitHub Desktop.
Mutation methods as a type, allowing easy copies to be made
struct Person {
var firstName, lastName: String
mutating func makeScottishClan() {
lastName = "mc\(lastName)"
}
}
// Person.Mutation gets automatically created (like an enum)
// .firstName(String)
// .lastName(String)
// .makeScottishClan
let john = Person(firstName: "John", lastName: "Doe")
// Make copy with mutations (Person.Mutation are written in full to show what is happening)
let carol = john mutating [
Person.Mutation.firstName("Carol"),
Person.Mutation.makeScottishClan
]
// Or can shorten to:
let alice = john mutating [
.firstName = "Alice",
.makeScottishClan
]
// Can shorten to one line when just a single mutation:
let robert = alice mutating .firstName = "Robert"
@RoyalIcing
Copy link
Author

RoyalIcing commented Apr 15, 2016

I wonder if you did have something like this with a = , could it complicate parsing? Or not read as declarativel?

let robert = alice mutating .firstName = "Robert"

vs the less natural:

let robert = alice mutating .firstName("Robert")

@RoyalIcing
Copy link
Author

The array passed to mutating could be dynamic, allowing a series of mutations to be built up, stored, or applied to multiple values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment