It was random, and it survived.
Every single part of an organism goes through a recombination/mutation process countless times, the stinger evolved to be what it is today over a very long time and it's cool to study why it ended up the way it did. Tells us about their environment and history and evolutionary pressures, survival is a result of the random traits being successful in their context in specific ways.