How do you switch places with a named mob with commands?
Solution 1:
The problem is that you can't just teleport one entity to another and then the other one to the first one, because at that point they're both at the same location. You need some reference to the original location. This can be done in many ways, two of the most straightforward ones are:
The easy way: A dummy entity. You summon an armour stand at entity A, teleport entity A to entity B, teleport entity B to the armour stand and then kill the armour stand again. This is very similar to how values of two variables are usually swapped in programming, by introducing a third one as a temporary placeholder.
Let's say we want to swap the closest player with a mob called "Horst":
/execute at @p run summon armor_stand ~ ~ ~ {Tags:["teleportHelper"],NoAI:1,NoGravity:1,Marker:1,Invisible:1}
/tp @p @e[name="Horst",limit=1]
/tp @e[name="Horst"] @e[tag=teleportHelper,limit=1]
/kill @e[tag=teleportHelper]
The proper way: A function. You can execute a function at the position of entity A (and also as
it, for convenience), which teleports A to B, but the rest of the function still has the same execution position, you can teleport B to the old position of A. This way you do not need a dummy entity, which causes a tiny bit less lag.
Execute the function like this:
/execute as @p at @s run function example:whatever
In the "example" namespace of your datapack, have a function called "whatever" with this content:
tp @s @e[name="Horst",limit=1]
tp @e[name="Horst"] ~ ~ ~
Solution 2:
You could do it by summoning an armor stand (with a unique tag) at yourself, TPing to the mob, TPing the mob to the armor stand, and killing the armor stand.
execute at [PLAYER] run summon minecraft:armor_stand ~ ~ ~ {Invisible:1b,Invulnerable:1b,Tags:["mobPlayerSwapper"]}
execute as [PLAYER] run tp @s [MOB]
execute as @e[tag=mobPlayerSwapper] run tp [MOB] @s
kill @e[tag=mobPlayerSwapper]