Using dispatch_async with itself

I came across this problem several times when porting Objective-C code to Swift. Let's say I have the following code:

dispatch_async(dispatch_get_main_queue()) { self.hostViewController?.view.addSubview(self.commandField) } 

This will result in an error underlining the entire dispatch_async call, suggesting:

 Could not find member 'addSubview' 

I assume this is an error that has not yet been properly implemented, because if I put the addSubview call outside the dispatch_async block, the project will be obstinate. Initially, I assumed that this might have something to do with capturing self in a block. However, inserting [unowned self] in leads to the same error as [weak self] in (after the corresponding spread operators were inserted ! ).

How can I get dispatch_async blocks to work in Swift that need to capture self ?

+42
swift grand-central-dispatch
Jun 07 '14 at 1:29
source share
2 answers

You should agree to cancel this action for non-nullity, and not test it after you have already initiated it:

 if let hostView = self.hostViewController?.view { DispatchQueue.main.async { hostView.addSubview(self.commandField) } } else { // handle nil hostView } 

You should never deploy an option outside if let or test it first. Doing this should also solve your weak kernel problem.

+65
Jun 07 '14 at 1:50
source share

The syntax for dispatch_async has changed using Swift 3:

 DispatchQueue.main.async { hostView.addSubview(self.commandField) } 
+12
Jun 13 '16 at 23:16
source share



All Articles