0

Already Tried these:

'dispatch_once_t' is unavailable in Swift: Use lazily initialized globals instead

Whither dispatch_once in Swift 3?

Here is my code: enter image description here

class var sharedInstance:Model{
        struct Static{
            static var instance:Model?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token){
            Static.instance = Model()
        }
        return Static.instance!

    }

Please suggest me alternative method for dispatch_once_t..I dont know swift, I code C/C++/Obj.C, please give me swift code to fix above problem

Hamish
  • 78,605
  • 19
  • 187
  • 280
iPhoneProcessor
  • 4,980
  • 6
  • 27
  • 49
  • Alternative for `dispatch_once()` or rather a good way to make singleton (commonly named `sharedInstance` in Objective-C) ? That's a different question. For singleton: https://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift ? Mimicing exactly another language and not adapt it to your current one is not recommended. – Larme Jun 30 '17 at 15:39
  • @Larme, thanks for your suggestions. Please give me swift version of code to fix above error...please answer – iPhoneProcessor Jun 30 '17 at 15:46

1 Answers1

5

In swift singleton can be written as,

class Model: NSObject {
    static let sharedInstance = Model()
}

then use Model.sharedInstance. you dont need dispatch once like in objective c.

source https://thatthinginswift.com/singletons/

adev
  • 2,052
  • 1
  • 21
  • 33