Example of dispatch_once in Swift

前端 未结 3 556
终归单人心
终归单人心 2020-12-30 06:36

Is there an example of how dispatch_once should be used in Swift? (Preferably one from Apple.)

Note: In this case, I\'m not using it for a singleton

3条回答
  •  余生分开走
    2020-12-30 06:48

    the robertvojta's answer is probably the best. because i try always to avoid import Foundation and use 'pure' Swift solution (with Swift3.0 i could change my opinion), I would like to share with you my own, very simple approach. i hope, this code is self-explanatory

    class C {
        private var i: Int?
        func foo()->Void {
            defer {
                i = 0
            }
            guard i == nil else { return }
            print("runs once")
        }
    }
    
    let c = C()
    c.foo() // prints "runs once"
    c.foo()
    c.foo()
    
    let c1 = C()
    c1.foo() // prints "runs once"
    c1.foo()
    
    class D {
        static private var i: Int?
        func foo()->Void {
            defer {
                D.i = 0
            }
            guard D.i == nil else { return }
            print("runs once")
        }
    }
    
    let d = D()
    d.foo() // prints "runs once"
    d.foo()
    let d2 = D()
    d.foo()
    

提交回复
热议问题