Maximiliano Richeze (Deceuninck-Quickstep) finished off the leadout perfectly for Viviani, leading him through the final corner with plenty of speed and leaving the rest of the field with little chase to overtake.
In the end Peter Sagan (BORA-hansgrohe) was only able to hold the Italian's wheel in the final hundred metres and the pair gapped the field, with Jasper Stuyven finishing well adrift in third.
"It’s always good to win a race," said Viviani, "and getting to taste victory for the second day in a row feels great. The guys did a perfect job and I must say they make my life much easier. This success makes me happy also because it confirms I’m on track for the Tour de France.”
The journey from Münchenstein to Einsiedeln for the 177km-long stage was by no means a walk in the park, despite coming down again to a mass sprint. A hilly route featuring a 13 kilometre second-category climb inside the last 40 kilometers tested the bunch and inspired Matej Mohoric (Bahrain Merida), Bert-Jan Lindemann (Jumbo-Visma), Stefan Küng (Groupama-FDJ) and Fabien Grellier (Total Direct Energie) to break away.
The peloton worked hard to bring the escapees back and caught them with 15 kilometres to go and the sprint teams began preparing for the finish.
“We all had tired legs," said Viviani, "because the stage was really hard, and knowing that the uphill finish and the cobbles would make everything tactical, I asked the guys to move to the head of the bunch with only 1500 metres left.
"After Max dropped me off the front as we rounded the last corner, all I had to do was launch my sprint. The flat stages are over, but I will continue the race, help as much as possible Enric, who is our GC guy, and hopefully get to celebrate some more nice results with the team.”
Sagan was the first rider to congratulate Viviani over the line but the three-time world champion at least had the consolation of retaining his overall lead in the race, if only for one more day.
Sagan extended his lead on the general classification out to 14 seconds over Matthews but the battle for overall is set to change dramatically on stage 6 with the race heading towards the mountains.