Create shared instance of observer

I'm trying to follow the guide to setup apple pay in-app purchases and it says here:


Consider creating your observer as a shared instance of the class for global reference in any other class.

If I have:

Code Block
class StoreObserver: NSObject, SKPaymentTransactionObserver {
....
//Initialize the store observer.
override init() {
super.init()
//Other initialization here.
}
//Observe transaction updates.
func paymentQueue(_ queue: SKPaymentQueue,updatedTransactions transactions: [SKPaymentTransaction]) {
//Handle transaction states here.
}
....
}


and I call it with: let iapObserver = StoreObserver()

how do I create such shared instance?
Answered by Developer Tools Engineer in 616679022
This bit of the documentation is suggesting that you consider making StoreObserver a singleton—an object that (at least in non-test code) only has one instance—so that all of your store observation is handled by a single instance that’s aware of all the other observation done elsewhere in your app. To do this, you would write the class like this:

Code Block swift
class StoreObserver: NSObject, SKPaymentTransactionObserver {
static let shared = StoreObserver()
....
// ...as before...

And then always use StoreObserver.shared, not the initializer, when you need a StoreObserver.
Accepted Answer
This bit of the documentation is suggesting that you consider making StoreObserver a singleton—an object that (at least in non-test code) only has one instance—so that all of your store observation is handled by a single instance that’s aware of all the other observation done elsewhere in your app. To do this, you would write the class like this:

Code Block swift
class StoreObserver: NSObject, SKPaymentTransactionObserver {
static let shared = StoreObserver()
....
// ...as before...

And then always use StoreObserver.shared, not the initializer, when you need a StoreObserver.
Create shared instance of observer
 
 
Q