Gaetano Herman Gaetano Herman - 1 year ago 91
Swift Question

Add Object to list on initialization

is there any way to add an object to a list when creating it with Swift? I think you can do this with Java by doing

.add(this)
but I'm not sure on how to do it in Swift. This is the code I have right now. Doing the append doesn't seem to work as the list stays empty.

public struct Candle {
let id: Int
let name: String
let burning: Bool
let type: CandleType

var differentCandles: [Candle] = []

init(name: String, burning: Bool, candleType: CandleType) {
self.name = name
self.burning = burning
self.type = candleType
self.id = differentCandles.count + 1
differentCandles.append(self)
}
}

Answer Source

The method .append(item) is the good way to add an item to an array but in your case you're creating a retain cycle that will leak your application.

Your var differentCandles should be save somewhere else, or be static.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download