Serial Numbers

macOS 10.11/Xcode 8.0

Sometimes, you want items to have serial numbers. This is, to me, the neatest way of creating such unique identifiers – simply use a static variable, and assign it to each new item before incrementing it in the initialiser.

class HazSerialNumber {
static var serialCounter: Int = 1

let serial: Int

init(){
self.serial = HazSerialNumber.serialCounter
HazSerialNumber.serialCounter += 1
}

}

You could also use this to keep a running count of how many objects you have – use a counter and decrease it in deinit. Here you trade a little computing power every time an object is instantiated for the potential cost in calculating the total number of items you have around. (Sometimes, you just need to know.)

Lazy vars are not threadsafe, so keep that in mind: if your architecture allows the creation of multiple objects from multiple locations, this might lead to problems.

Alternatively, people have written serial number variables to UserPreferences, which is just a fancy way of setting up a singleton to handle this.