I have run into this problem a few times while porting Objective-C code to Swift. 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, offering:
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 builds fine. Initially I assumed it may have something to do with capturing self
in the block. However, inserting [unowned self] in
results in the same error, as does [weak self] in
(after the appropriate !
unwrap operators have been inserted).
How can I get dispatch_async
blocks to work in Swift that need to capture self
?
您应该对非null取消该操作的条件,而不是在启动它后再对其进行测试:
if let hostView = self.hostViewController?.view {
DispatchQueue.main.async {
hostView.addSubview(self.commandField)
}
} else {
// handle nil hostView
}
您切勿在之外打开可选的包装if let
或先对其进行测试。这样做还应该解决自己的自我弱点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句