You should condition spinning off this action on the non-nullity, not test for it after you’ve already initiated it:
if let hostView = self.hostViewController?.view {
DispatchQueue.main.async {
hostView.addSubview(self.commandField)
}
} else {
// handle nil hostView
}
You should never unwrap an optional outside of an if let, or testing it first. Doing this should also resolve yer weak self issue.