TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Creating Singleton with Public Init Parameters

Forums > Swift

I'm trying to create a singleton, but the Class 'IAPHelper' it's instantiating has a public init method that takes a parameter.

I can't see how to pass the required parameter, so I get the error message:

"Cannot use instance member 'productIdentifiers' within property initializer; property initializers run before 'self' is available"

open class IAPHelper: NSObject  {

    private let productIdentifiers: Set<ProductIdentifier>
    private var purchasedProductIdentifiers: Set<ProductIdentifier> = []
    private var productsRequest: SKProductsRequest?
    private var productsRequestCompletionHandler: ProductsRequestCompletionHandler?

    static let shared = IAPHelper(productIds: productIdentifiers)  

    public init(productIds: Set<ProductIdentifier>) {
        productIdentifiers = productIds
        for productIdentifier in productIds {
            let purchased = KeychainWrapper.standard.bool(forKey: productIdentifier)
            if purchased ?? false {
                purchasedProductIdentifiers.insert(productIdentifier)
                print("Previously purchased: \(productIdentifier)")
            } else {
                print("Not purchased: \(productIdentifier)")
            }
        }
        super.init()

        SKPaymentQueue.default().add(self)
    }
}

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.