For var bug?

I am completely lost. This code is intended to print a bunch of 1s, but it outputs 8! What am I missing if anything?

class Mocha {var i = 0}
let arr = Array.init(repeating: Mocha(), count: 8)
for var instance in arr {
    instance.i += 1 //Variable 'instance' was never mutated; consider removing 'var' to make it constant. WHAT?
for i in arr { print(i.i) }

Why on earth this doesn't print 1?

Mocha is a class, with reference semantics. Your array has the same Mocha instance repeated eight times. In the initisliser of your array, you create a single Mocha instance and instructs the array to contain it eight times. Then, you iterate over your array, each time getting the same instance, and each time incrementing its i field, until it finally reaches the value of 8.

1 Like

You can solve the issue by either:

  • Making Mocha a struct, or
  • Replacing your array construction with a simple loop or map that creates eight different Mochas

Gosh :flushed:, so its basically

class Mocha {var i = 0}
let a = Mocha()
var arr : [Mocha] = []
for _ in 0..<8 { arr.append(a); a.i += 1 }
arr.forEach {print($0.i)}

Huh, lovely, thank you for pointing this out. I thought that I am was going out of my mind.

1 Like