The tone of the story (as told in Mark 5:1-20) suggests to me that the legion are tricked. The unclean spirits know they are no match for Jesus' power and so they resort to begging him. They would rather enter the swine than be cast out of the region. They would rather take up residence in a body, even a pig's body, than be forced to wander the land without a host. (While other ancient Jewish writings speak about unclean spirits tormenting people, the Gospels are somewhat distinctive in their emphasis on these kinds of malevolent spirits possessingpeople. This story is consistent with that, in that the spirits want to be inside of -- or part of -- a body.)
What makes this a trick is that the pigs end up dying in the water, taking the unclean spirits with them. The implication is that this is the end of the trail for those unclean spirits, too. The water represents chaos, the deep, the dead. The spirits thought they could survive their encounter with Jesus but his goal is to destroy these harmful influences, not simply to relocate them. The story is unclear about why the pigs stampede into the water, which is unusual behavior to say the least. It isn't clear whether the spirits somehow drive the pigs wild or whether something or someone else causes this. The story isn't interested in answering that question. The focus is that here is a powerful foreign army (in this case, consisting of unclean spirits) dead in the water, just like Pharaoh's soldiers in the story of the Exodus from Egypt, prevented from doing any more harm. No one seems to mourn the loss of what might have been many pigs (a legion consisted of between 3000-6000 Roman soldiers), but that's because the story is more interested in celebrating Jesus' power as a liberator (see also Mark 3:23-27). He delivers the afflicted man from a horrible oppression. The story's perspective toward the unclean spirits is: good riddance.