patternswiftMinor
Singleton class with custom initializer
Viewed 0 times
withcustomsingletonclassinitializer
Problem
In a Swift project, I have a class should be used as a
This class helps me communicate between several nearby devices and the
What makes me wondering about this class is that each time I call it goes like this:
First, I am creating a reference to the manager and line after it I set some value on its property. How can I improve this design?
singleton:class NearFieldManager : NSObject{
static let shared = NearFieldManager()
var dataToTransfer:Any!
}This class helps me communicate between several nearby devices and the
dataToTransfer is some information each device is advertising about itself.What makes me wondering about this class is that each time I call it goes like this:
let manager = NearFieldManager.shared
shared.dataToTransfer = "some data"First, I am creating a reference to the manager and line after it I set some value on its property. How can I improve this design?
Solution
Assuming the
dataToTransfer is always the same for a specific device, you can create this data in init()class NearFieldManager {
static let shared = NearFieldManager()
private let dataToTransfer: Any
private init() { //private to forbid instantiation
self.dataToTransfer = methodToCreateDeviceData()
}
}Code Snippets
class NearFieldManager {
static let shared = NearFieldManager()
private let dataToTransfer: Any
private init() { //private to forbid instantiation
self.dataToTransfer = methodToCreateDeviceData()
}
}Context
StackExchange Code Review Q#152024, answer score: 5
Revisions (0)
No revisions yet.