NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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)
    }
}

   

Hacking with Swift is sponsored by Stream

SPONSORED Check out Stream's cross-platform open source chat SDK on GitHub! Write once and deploy your app with fully featured chat UI on iOS and macOS.

Go to GitHub

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

Reply to this topic…

You need to create an account or log in to reply.

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.