"you hire a replacement and risk being stuck with unnecessary employees in 3 years"
That is not how it works in Sweden (nor anywhere else that I know of). The replacement is hired as a temporary position until the original employee returns.
Even if that's the case, you would most likely get an employee of lower quality or with a lower commitment if they know they will be laid off in 3 years.
But in this case, the discrimination is rational. Due to maternity leave, a woman of equal skill creates significant cash flow risks - if she takes leave, you either go for 3 years with her job not getting done, or else you hire a replacement and risk being stuck with unnecessary employees in 3 years.