Switzerland's neutrality was guaranteed by the Congress of Vienna in 1815 and so far has held up in spite of various unpleasantness in Europe. Part is due to tradition, part of it is the ingrained Swiss instinct not to choose sides and part is Switzerland is just not very strategically desirable land.
Switzerland's neutrality wasn't under much threat from the warring powers in World War I. Even so, Switzerland mobilized its army and deployed most of its troops on its border with France though it stood down almost all its troops over the course of the war. In the trench warfare of World War I none of the belligerents regarded Switzerland as a easy invasion route to the enemy's heartland.
Hitler was no respecter of international treaties so Switzerland was under relatively greater threat in World War II.
However, Hitler didn't see Swiss Germans as naturally belonging to his Pan-Germanic empire and there was little affinity among Swiss Germans with Nazi Germany.
Switzerland was not the product of the Treaty of Versailles that Hitler was determined to undo so Switzerland was not among the first of Hitler's targets.
Switzerland was somewhat awkwardly placed for the Axis, limiting rail connections between Germany and Italy to the Brenner Pass. The Brenner Pass was apparently enough for Germany and Italy, though some non-military related goods passed over the Swiss rail system between Germany and Italy.
In short, Switzerland maintained its neutrality by its tried and true methods: being useful to the warring sides without committing to either, having a big enough army to keep from looking like a pushover and being in a part of Europe that is not a natural invasion route between France and Germany.
So far no evidence has been turned up showing that German or Italian troops, concentration camp inmates or forced laborers passed over Swiss railroads. Some military goods and dual-use cargoes did but the traffic was not large and was further restricted over the course of the war