As I understand, swords have historically been rather expensive and difficult to make. Further, there is some evidence that especially in large-scale formation combat the spear is superior. So, why did Republican Rome relegate the spear to the elite, reserve Triarii and equip front line troops with swords?
The Roman legions, as described by Polybius, consisted of:
velites, who fought as unarmoured javelineers
hastati, who fought as armoured infantry, equipped with sword and shield, and heavy and/or light javelins
principes and triarii, who fought as armoured infantry, equipped with sword, shield, and long spear
The hastati, triarii, and principes all had armour, shield, sword, and spear(s). Everybody had spears! The difference is that the spears carried by the hastati were javelins, intended for throwing.
Against other armies that mostly used spear and shield and/or sword and shield, it's nice to have plentiful missile weapons, and having the hastati as javelineers as wells as the velites provides this.
But consider the Macedonian phalanx, with two-handed pikes as their key weapon. One-handed spear and shield can do rather badly against such a formation. Now having lots and lots of javelineers is no longer just nice, but essential. Disrupt the phalanx enough with javelins, and you have a good chance. This doesn't always work, and the Romans often lost against the pike phalanx (e.g., the Romans being on the losing side of Pyrrhic victories). The other choice the Romans could have made is to adopt the two-handed pike themselves, which would have put them on equal terms with other pike users. But the pike phalanx, while a formidable beast, is also a clumsy beast. As Polybius noted,
the Macedonian phalanx is difficult, and sometimes impossible to handle, because the men cannot act either in squads or separately.
For naval warfare, for fighting in forests, in mountains, in cities, against bandits, against hit-and-run guerrillas, a legionary Roman soldier has tactical flexibility and mobility than a phalangite with a pike doesn't have.
Considering that the principes and triarii carried swords in addition to their spears, switching from spear to sword as a primary weapon won't be expensive (or even cost anything). Also, perhaps the change is better described as switching from the hand-to-hand spear to the javelin as the main weapon.
(Partly adapted from my discussion in https://www.reddit.com/r/AskHistorians/comments/ae3b17/if_spears_were_generally_better_than_swords_why/ which might be of interest for further reading.)