Why does each neuron generate the same UUID when I instance a new one?

Viewed 43
import Foundation

struct Neuron {
    let id = UUID()

    func doSomeStuff() {
    // stuff
    }
}

let layer:[Neuron] = Array(repeating: Neuron(), count: 5)

When running:

for neuron in layer {
    print(neuron.id)
}

Every Neuron object gets given the same UUID instead of its’ own unique ID. I feel like I’m just missing the obvious here, or I’m misunderstanding how structures work?

I’m having the same issue with other properties in my full code but this is a cut down version for ease.

Thanks!

1 Answers

You are not generating a new instance. You are repeating the same instance in your collection. If you would like to create new instances you would need to create a range and map your struct initializer.

let layer = (1...5).map { _ in Neuron() }
Related