I already know the advantage of immutability over variability in the ability to talk about code and introduce fewer errors, especially in multi-threaded code. However, when creating structures, I see no benefit from creating a completely immutable structure over a mutable version.
Let as an example of a structure that stores a certain score:
struct ScoreKeeper {
var score: Int
}
In this structure, I can change the value of the estimate for an existing structural variable
var scoreKeeper = ScoreKeeper(score: 0)
scoreKeeper.score += 5
println(scoreKeeper.score)
An immutable version will look like this:
struct ScoreKeeper {
let score: Int
func incrementScoreBy(points: Int) -> ScoreKeeper {
return ScoreKeeper(score: self.score + points)
}
}
And its use:
let scoreKeeper = ScoreKeeper(score: 0)
let newScoreKeeper = scoreKeeper.incrementScoreBy(5)
println(newScoreKeeper.score)
, , , . , . , mutable, , .
, , . - , ?