Last active
April 22, 2016 08:09
-
-
Save RoyalIcing/ba2ce9dfd49595dacce07394de579172 to your computer and use it in GitHub Desktop.
Mutation methods as a type, allowing easy copies to be made
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
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
I wonder if you did have something like this with a = , could it complicate parsing? Or not read as declarativel?
vs the less natural: