Your question is Retain Cycle in Code. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
At a Tier 1 Bank, you're reviewing the transaction confirmation screen of the retail mobile banking app before it ships. QA has flagged that the screen sometimes stays alive in memory (visible via Instruments) even after the customer backs out of it.
class TransactionConfirmViewController: UIViewController {
var accountService: AccountService
var onConfirmed: (() -> Void)?
weak var delegate: TransactionConfirmDelegate?
var refreshTimer: Timer?
init(accountService: AccountService) {
self.accountService = accountService
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError() }
func loadBalance() {
accountService.fetchBalance { balance in
self.updateBalanceLabel(balance)
}
}
func startAutoRefresh() {
refreshTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
self.loadBalance()
}
}
func confirmTransaction(amount: Decimal) {
self.onConfirmed = {
self.dismiss(animated: true)
}
accountService.submitTransaction(amount: amount) { result in
self.handleResult(result)
self.onConfirmed?()
}
}
func updateBalanceLabel(_ balance: Decimal) { }
func handleResult(_ result: TransactionResult) { }
}
Explain what a retain cycle is under Swift's ARC memory model, then go through this class piece by piece and say precisely which parts of it do and do not create one. This is a free-text answer, not a code edit, so explain what you would change and why rather than submitting a fixed file.