1

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!

Konstantinos Natsios
  • 2,874
  • 9
  • 39
  • 74
  • 1
    Example here with an array, easy to adapt for dictionary: http://stackoverflow.com/a/35440014/2227743 You can also have a look at http://stackoverflow.com/a/36012158/2227743. – Eric Aya Aug 13 '16 at 11:01
  • 1
    You can try like this http://stackoverflow.com/a/38825263/6433023 – Nirav D Aug 13 '16 at 11:03

2 Answers2

3

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.

Marco Santarossa
  • 4,058
  • 1
  • 29
  • 49
2

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())
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148