From the Super Mario Wiki
Swords are traps that are found in Yoshi's Story. There are two different kinds of Swords. One of them is the Blue Sword, which only stabs up from the ground, from the ceiling, or from the left or right sides of walls. These types are almost never hidden. The other type of Sword is the Red Sword, which pops out of the ground and moves horizontally or vertically from a certain point and then back to its place of origin. These types of traps appear only in the level Mecha Castle. On a side note, Swords act in a similar manner to the spiked pillars from Super Mario World.