How to access associated value of a switch case, which itself is in a trailing closure

Viewed 96

As follows, what expression should I write to access let learningList? In the code, query is a class, find is a function. Many thanks!

        _ = query.find { result in
            switch result  {
            case .success(objects: let learningList):
                break
            case .failure(error: let error):
                print(error)
            
            }
        }
1 Answers

That is a local variable, so you can access it only in the decelerated context, i.e. inside case. If you need to use it later you have to create a property in caller class to hold it, like

_ = query.find { [weak self] result in     // << ref to caller
    switch result  {
    case .success(objects: let learningList):
        self?.learningList = learningList     // << safe in caller's property
        break
    case .failure(error: let error):
        print(error)
    
    }
}
Related