Refactored swap function.