Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Singleton

I'm currently working on a Shopify Application that uses their mobile buy sdk, and I'm trying to save the cart using a Singleton in Swift. I have a Singleton class that's set up like so:

class Singleton {

   static let sharedInstance = Singleton()

   init() {
     var cart = BUYCart()
     println(cart)
   }
}

When it gets initialized, it prints the BUYCart in the console. The problem is I'm trying to access the saved cart in a controller like so:

  println(Singleton.sharedInstance.cart.lineItems)

I get the following error:

 Singleton does not have member named 'cart'
like image 762
Alex Smith Avatar asked Sep 01 '26 04:09

Alex Smith


1 Answers

You should declare the variable at instance level. In your code its declared inside the constructor, so you can only access it inside the constructor. Not from outside the class like you are doing in your code.

class Singleton {

   static let sharedInstance = Singleton()
   var cart = BUYCart()

   init() {
     println(cart)
   }
}
like image 97
Raymond Avatar answered Sep 03 '26 18:09

Raymond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!