Skip to content

Instantly share code, notes, and snippets.

@jarsen
Last active September 6, 2019 02:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarsen/41de7401d49cd2348e5f to your computer and use it in GitHub Desktop.
Save jarsen/41de7401d49cd2348e5f to your computer and use it in GitHub Desktop.
example of copy constructor with default values for immutability
struct Scorekeeper {
let runningScore: Int
let climbingScore: Int
let bikingScore: Int
let swimmingScore: Int
init(runningScore: Int = 0, climbingScore: Int = 0, bikingScore: Int = 0, swimmingScore: Int = 0) {
self.runningScore = runningScore
self.climbingScore = climbingScore
self.bikingScore = bikingScore
self.swimmingScore = swimmingScore
}
init(scoreKeeper: Scorekeeper, runningScore: Int? = nil, climbingScore: Int? = nil, bikingScore: Int? = nil, swimmingScore: Int? = nil) {
self.runningScore = runningScore ?? scoreKeeper.runningScore
self.climbingScore = climbingScore ?? scoreKeeper.climbingScore
self.bikingScore = bikingScore ?? scoreKeeper.bikingScore
self.swimmingScore = swimmingScore ?? scoreKeeper.swimmingScore
}
func incrementRunningScoreBy(points: Int) -> Scorekeeper {
return Scorekeeper(scoreKeeper: self, runningScore: self.runningScore + points)
}
}
@NorakGithub
Copy link

This is a great idea. I have question, what would you do, says you have an array of Scorekeepers and you want to update element where runningScore equal to 10 and also the position of element after updated has to be the same as it were. I don't know how to approach this in Functional Programming way. Could you enlighten me?

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