sw: factor out a function to encapsulate object lifetimes

Change-Id: Ie49cb4729d70f2b1fee9a2b7bd4ac095732a3d58
sw: actually check that iterator is valid

Change-Id: Icefedf1d3fe09ed6670481dcdc4c5e745e816b1b