Search code examples
iosswiftasynchronousescapingclosures

Swift: should completion closure have error indication when weak self is nil?


I have a function that takes an escaping completion closure:

func doTheWork(completion: () -> Void) {
    process { [weak self] in
        guard let self = self else {
            return
        }
        completion()
    }
}

The question is if weak self turns out to be nil, is it common to still call completion() before return? I guess it depends on the scenario, I'm just thinking in general, if the object itself is nil when the closure is invoked, what's the point of notifying the work has completed? On the other hand, if the user of the object isn't nil while the object itself is nil for whatever reason, the user of the object should still know the work has (NOT) completed, so that means the completion closure should indicate whether the work has finished, probably with a Bool argument in it?

Thanks!


Solution

  • It's up to ur purpos. If u just want stop process without callback, u can do like this. If u want to distinguish success or fail, u can return by Bool or Error.

    func doTheWork(completion:@escaping((_ success:Bool)->Void)) {
        process { [weak self] in
            guard let self = self else {
                completion(false)
                return
            }
            completion(true)
        }
    }
    
    func printJsonStr(_ jsonUrl:URL,completion:@escaping((_ error:Error?)->Void)) {
        do {
            let data = try Data(contentsOf: jsonUrl)
        } catch {
            completion(error)
        }
        completion(nil)
    }