My understanding is that the “sword” referred to Mary suffering along with Jesus during His Passion. She witnessed it all and suffered with him right up till He died.
Other saints have also suffered physical pain, including in some cases heart pain, as a way of joining Christ in his suffering, as “victim souls” who offer their suffering in reparation for the sins of the world. This to me is similar to the sword that pierced Mary’s sorrowful heart.
In other cases, like St. Teresa of Avila whose heart was pierced, it was more like God infusing his fire of love into her. Mary already loved God probably more than any other human, so there would have been no need for a sword to pierce her heart to infuse God’s love.