It may be useful to include a small reset delay in your program, before you reconfigure the SWD pins. I typically use values in the order of 100ms to 1s. This can be useful to prevent "bricking" the MCU, for example, if you reconfigure SWD pins, disable/reconfigure the system clock accidently, or enter shutdown mode.
Some reprogramming/flashing routines will issue a system/hardware reset on the MCU before attempting to reprogram. Technically this is not necessary if the debugger can halt the MCU core and reprogram it straight away. However with a system reset, the MCU will start from a known state. When the start-up delay is sufficiently long, reconfiguration of the SWD pins is postponed such that the debug interface stays accessible long enough to halt the MCU and start rewriting the FLASH memory.
Alternatively on most STM32 chips, you can pull the BOOT0 pin to enter the ROM bootloader (the datasheet lists if you need to pull it high or low). The ROM bootloader doesn't touch the SWD pins, and therefore the MCU remains accessible via SWD. However, this usually requires a manual intervention, especially if you don't got a button or jumper attached to this pin, so it gets tiresome real fast if you reprogram the MCU often.