Is it safe to force unwrap variables that have been optionally accessed in the same line of code?

后端 未结 5 940
无人及你
无人及你 2020-12-14 05:52
someFunction(completion: { [weak self] in
    self?.variable = self!.otherVariable
})

Is this always safe? I access the optional <

5条回答
  •  春和景丽
    2020-12-14 06:42

    Is this always safe

    No. You are not doing the "weak-strong dance". Do it! Whenever you use weak self, you should unwrap the Optional safely, and then refer only to the result of that unwrapping — like this:

    someFunction(completion: { [weak self] in
        if let sself = self { // safe unwrap
            // now refer only to `sself` here
            sself.variable = sself.otherVariable
            // ... and so on ...
        }
    })
    

提交回复
热议问题