Konstantinos Natsios
Konstantinos Natsios

Reputation: 2924

How to create a proper singleton for Dictionary in Swift 2

I have the following code

class Test: UIViewController {
  var imagesOfChef = [Int : chefImages]()
    struct chefImages {
          var objidChef: String!
          var imageChef: UIImage!
      }

}

I fill up this dictionary as soon as the user opens the application. But i want it to be available also in other Views (swift files)

Lets say in this class

class Test2: UIViewController{

}

How can i create a singleton for this Dictionary so it can be available to other views?

Thanks for your time!

Upvotes: 1

Views: 960

Answers (2)

Marco Santarossa
Marco Santarossa

Reputation: 4066

You can use a static property:

static var imagesOfChef = [Int : chefImages]()

and then you use:

Test.imagesOfChef 

But I suggest avoiding the static approaches as much as possible, you can use the prepare segue or assign the property from outside if possible if Test has Test2.

Upvotes: 3

Luca Angeletti
Luca Angeletti

Reputation: 59526

There are plenty of examples on StackOverlow about how to create a Singleton.

Anyway, your code should be like this

struct Chef {
    let id: String
    let image: UIImage
}

final class Singleton {
    static let sharedInstance = Singleton()
    private init() { }        
    var dict = [Int: Chef]()
}

Now in any source of your app you can use it

Singleton.sharedInstance.dict[1] = Chef(id: "1", image: UIImage())

Upvotes: 2

Related Questions