Comment puis-je exécuter du code une seule fois dans Swift?

Les réponses que j'ai vu jusqu'à présent (UnDeuxTrois) vous recommandons d'utiliser le PGCD de dispatch_once ainsi:

var token: dispatch_once_t = 0
func test() {
    dispatch_once(&token) {
        print("This is printed only on the first call to test()")
    }
    print("This is printed for each call to test()")
}
test()

De sortie:

This is printed only on the first call to test()
This is printed for each call to test()

Mais attendez une minute. token est une variable, donc j'ai pu facilement le faire:

var token: dispatch_once_t = 0
func test() {
    dispatch_once(&token) {
        print("This is printed only on the first call to test()")
    }
    print("This is printed for each call to test()")
}
test()

token = 0

test()

De sortie:

This is printed only on the first call to test()
This is printed for each call to test()
This is printed only on the first call to test()
This is printed for each call to test()

Donc dispatch_once est d'aucune utilité si nous je peux changer la valeur de token! Et en tournant token dans une constante n'est pas simple, car il doit de type UnsafeMutablePointer<dispatch_once_t>.

Donc devrions-nous renoncer à dispatch_once dans Swift? Est-il un moyen plus sûr pour exécuter le code qu'une fois?

source d'informationauteur Eric