Skip to content

Instantly share code, notes, and snippets.

@jarsen jarsen/ScoreKeeper.swift
Last active Apr 19, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Apr 19, 2018

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
You can’t perform that action at this time.