DevPrep

All topics › Real interview tasks

Refactoring: find the real leak instead of sprinkling weak self

Senior PRO

Task

What's wrong with this controller? Find the leaks and bugs, and explain where [weak self] is needed and where it isn't.

final class FeedViewController: UIViewController {
    private let service = FeedService()
    private var timer: Timer?
    private var items: [Item] = []
    private let tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()

        service.onUpdate = { items in
            self.items = items
            self.tableView.reloadData()
        }

        timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] _ in
            self?.service.refresh()
        }

        service.load { [weak self] result in
            guard let self else { return }
            if case .success(let items) = result {
                self.items = items
                self.tableView.reloadData()
            }
        }
    }
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store