Refactored swap function