Swap defer with nil guard to avoid nil reference