2016-07-22 13 views
20

Mam problemy z dispatch_once_t podczas migracji do Swift 3.„dispatch_once_t” jest niedostępny w Swift: Użyj leniwie zainicjowane globalnych zamiast

Według Apple's migration guide:

The free function dispatch_once is no longer available in Swift. In Swift, you can use lazily initialized globals or static properties and get the same thread-safety and called-once guarantees as dispatch_once provided. Example:

let myGlobal = { … global contains initialization in a call to a closure … }()

_ = myGlobal // using myGlobal will invoke the initialization code only the first time it is used.

Więc chciałem przenieść ten kod . Tak było przed migracją:

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

    dispatch_once(&Static.token) { 
     Static.instance = CarsConfigurator() 
    } 

    return Static.instance! 
} 

po migracji, w następstwie wytycznych Apple (ręczne migracji), kod wygląda następująco:

class var sharedInstance: CarsConfigurator 
{ 
    struct Static { 
     static var instance: CarsConfigurator? 
     static var token = {0}() 
    } 

    _ = Static.token 

    return Static.instance! 
} 

Ale gdy uruchomię to pojawia się następujący błąd, gdy dostępu return Static.instance!:

fatal error: unexpectedly found nil while unwrapping an Optional value

widzę z tego błędu, że człon instance jest nil, ale dlaczego nie? Czy coś jest nie tak z moją migracją?

+1

'dispatch_once' usunięto' Swift 3'. Sprawdź [to] (http://stackoverflow.com/a/37801408/5654848) odpowiedź na pytanie, jak robić rzeczy "raz" zamiast tego. – Dershowitz123

Odpowiedz

15

Ten kod był zbyt gadatliwy, mimo że był ważny w Swift 2. W Swift 3, siły Jabłko używanie leniwe inicjowanie przez zamknięcie:

class CarsConfigurator { 
    static let sharedInstance: CarsConfigurator = { CarsConfigurator() }() 
} 
Powiązane problemy