Magnetic switchbacks are rapid high-amplitude reversals of the radial magnetic field in the solar wind that do not involve a heliospheric current sheet crossing. First seen sporadically in the 1970s in Mariner and Helios data, switchbacks were later observed by the Ulysses spacecraft beyond 1 au and have been recently discovered to be a typical component of solar wind fluctuations in the inner heliosphere by the Parker Solar Probe spacecraft. While switchbacks are now well understood to be spherically polarized Alfvén waves thanks to Parker Solar Probe observations, their formation has been an intriguing and unsolved puzzle. Here we provide a simple yet predictive theory for the formation of these magnetic reversals: the switchbacks are produced by the distortion and twisting of circularly polarized Alfvén waves by a transversely varying radial wave propagation velocity. We provide an analytic expression for the magnetic field variation, establish the necessary and sufficient conditions for the formation of switchbacks, and show that the proposed mechanism works in a realistic solar wind scenario. We also show that the theoretical predictions are in excellent agreement with observations, and the high-amplitude radial oscillations are strongly correlated with the shear of the wave propagation speed. The correlation coefficient is around 0.3–0.5 for both encounter 1 and encounter 12. The probability of this being a lucky coincidence is essentially zero with p-values below 0.1%.