The attached code has a singleton class, and a superclass based on it.
When I run the code, I get:
Singleton explicit init
Singleton explicit init
SuperClass explicit init
Base device count: 2
Singleton explicit init
SuperClass explicit init
Base device count: 2
Singleton explicit init
SuperClass explicit init
Base device count: 2
Device count: 3
- Why is the init() in the singleton class re-run every time a new instance of the superclass is created?
- Why is the print() in the static initialisation of the singleton class never executed?
- The singleton class is initialised with 2 elements in the deviceList array, but then has another element added at line 7 in func test(), yet each time a member of the superclass is subsequently initialised, the superclass only reports 2 elements in the deviceList. Why?
If the print line 30 in the SingletonClass explicit init() is commented out so that the compiler should eliminate it, the print() in the static initialisation still never happens, with the result:
SuperClass explicit init
Base device count: 2
SuperClass explicit init
Base device count: 2
SuperClass explicit init
Base device count: 2
Device count: 3
import Foundation
func test() {
let singletonClass = SingletonClass()
var superList = SuperClasssingletonClass.addDevice() for index in 0..<singletonClass.deviceList.count { superList.append(SuperClass(thisDevice: singletonClass.deviceList[index])) } print("Device count: \(superList.count)")
}
test()
struct Device: Identifiable {
let id: Int
}class SingletonClass {
static let shared: SingletonClass = {
let instance = SingletonClass()
print("Singleton init")
return instance
}()
var deviceList = [Device(id: 99), Device(id: 98)]init() { print("Singleton explicit init") } func addDevice() { let i = deviceList.count deviceList.append(Device(id: i)) }
}
class SuperClass: SingletonClass {
var thisDevice: Deviceinit(thisDevice: Device) { self.thisDevice = thisDevice super.init() print("SuperClass explicit init") print("Base device count: \(deviceList.count)");print() }
}
The code to create the Singleton comes from Apple
https://developer.apple.com/documentation/swift/managing-a-shared-resource-using-a-singleton
For explanation, the attached test code is extremely simplified, but the singleton class represents a Bluetooth BLEManager, and the devices are asynchronously found devices such as a heart rate monitor, a blood oxygen monitor, or similar, each of which needs to communicate through the singleton BLEManager.