Understand how to work with threads in Swift, found an example that looks like this

private func searchForTweets() { if let request = twitterRequest { request.fetchTweets { [weak self] newTweets in if let wSelf = self { dispatch_async(dispatch_get_main_queue()) { if !newTweets.isEmpty { tweets.insert(newTweets, at: 0) } } } } } } 

But in swift 3 , Dispatch was changed and I can’t find a normal tutorial (advise if you have it at hand. I didn’t find it in off-docks either)

So as I understood, I did it like this

 private func searchForTweets() { if let request = twitterRequest { request.fetchTweets { [weak self] newTweets in if let wSelf = self { DispatchQueue.global().async { if !newTweets.isEmpty { wSelf.tweets.insert(newTweets, at: 0) } } } } 

But I'm not sure that this is correct. I’m confused by the fact that in the example they are passed as the parameter dispatch_get_main_queue() , and I don’t pass anything on myself ...

    1 answer 1

     dispatch_async(dispatch_get_main_queue()) { <#code#> } 

    Now recorded

     DispatchQueue.main.async { <#code#> } 

    These questions are well covered on the eve of the release of Swift 3. Here is an article , for example.

    As for me, Swift 3 is very intuitive for recording. We answer 3 questions and write to the code:

     Что? Где? Как? DispatchQueue.main.async DispatchQueue.main.asyncAfter DispatchQueue.global().async и т.д. 

    A little bit about threads:

    Main queue - the main stream. Its main task is to execute code that displays the user interface. From the record DispatchQueue.main can see that this is a singleton , i.e. this thread is one.

    Never perform "heavy" tasks in the main thread, because This will cause freezes / friezes.

    In no case call the sync method on the Main queue , because this will result in the deadlock application.

    Global queue - global queues. To perform any tasks that should not be related to the main thread. For example, network queries, calculating the number of Pi, etc.

    Example of use:

     DispatchQueue.global().async { //Получаем данные с сервера DispatchQueue.main.async { //Отображаем полученные данные } }