Because the fetal pig doesn’t have access of air to breathe. The pig mother does the breathing for her fetus. Also, the lungs develop last, since they aren’t useful until after birth.
As for the mechanism, it is because the lungs haven’t begun to produce surfactant yet. The surfactant is a natural detergent that breaks the surface tension of the water in the lungs. Since there is so much surface area in the lungs, and the alveoli are so tiny, the surface tension of the thin layer of water in the lungs (necessary for gas diffusion) will hold the tiny spaces closed. Without surfactant, it would be almost impossible to inflate the lungs due to the force of the surface tension. (Wikipedia)