Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 631 Vote(s) - 3.45 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'dispatch_once_t' is unavailable in Swift: Use lazily initialized globals instead

#1
I am having trouble with `dispatch_once_t` when migrating to Swift 3.

According to [Apple's migration guide](

[To see links please register here]

):

> 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.`

So I wanted to migrate this code. So it was before migration:

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!
}

After the migration, following the Apple's guidelines (manual migration), the code looks like this:

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

_ = Static.token

return Static.instance!
}

But when I run this I get the following error when accessing `return Static.instance!`:

> fatal error: unexpectedly found nil while unwrapping an Optional value

I see from this error that the `instance` member is `nil`, but why is it? Is it something wrong with my migration?
Reply

#2
That code was overly verbose even though it was valid in Swift 2. In Swift 3, Apple forces you to use lazy initialization through closure:

class CarsConfigurator {
static let sharedInstance: CarsConfigurator = { CarsConfigurator() }()
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through