Swords are neat. Unfortunately, they aren't very practical with guns around. What sorts of technologies, social circumstances, environmental factors or magics would allow for people who train to fight primarily in melee to be competitive (or at least viable) as soldiers in a setting with common access to firearms or other, similarly effective, ranged weapons?
The primary reason melee weapons are not used in modern warfare is range. In the time it takes a sword wielding combatant to close the distance to a rifle wielding combatant, the rifleman has shot the swordsman multiple times.
There are two basic ways around this, both of which have seen use in history. Closing the distance faster, or just take the hits on the way in.
Close the distance faster
This could be reducing the distance itself, as in fighting in tight spaces, or covering that distance so fast that the rifleman does not have the chance to fire accurately.
Historical examples of the first include tunnel warfare and urban combat, where weapons often cannot be brought to bear fast enough on melee opponents. (Note that there are counters to this in the form of pistols, submachine guns, and short tactical shotguns) Futuristic warfare might adopt melee weapons if combat often took place in densely packed hive cities or in tight tunnel complexes or ship passages.
Covering the distance faster fell out of favor in our history due to the invention of the machine gun and the semi-automatic rifle. WWI being the last major war to employ traditional cavalry, for example. In the future, cybernetic or genetic augmentation might make humans fast enough and agile enough to approach a rifleman at speeds too great for him to react. In addition, short range teleportation in the form of the classic "blink" device could remove distance altogether.
Take the hits
The question of ranged combat vs melee combat has existed since the first human chucked a javelin at a guy with a club. For most of human history, however, the guy with the club has had access to some level of armor to deflect or stop ranged projectiles. This allowed him to effectively shrug off many of the projectiles directed at him, allowing him to close the distance and eliminate his adversary. Today, weapons technology has turned armor from near invincibility to a layer that just prevents you from dying instantly. In the future, however, armor technology might increase again to the point where a melee warrior could once more shrug off the bullets directed at him, letting him get close enough to put his weapon to use. Shields, kinetic absorbers, alloy plates, or even just genetically engineered super-regeneration (Wolverine) would make melee combat more viable. (At least until someone makes a better gun)
See Star Wars. If guns are ineffective and/or can be used against you via magic (see this answer for other points), then people will look for alternatives.
On the frontier. Guns require ammo. Specially in space settings (or zombie settings), ammo (or rather the components to make ammo) may be rare enough that people don't want to (or can't afford to) fire a bullet's weight in gold all the time. Even if melee wasn't preferred, it would likely still be common/trained.
Across the galaxy. Guns are great, but they're fairly well specialized to an oxygen atmosphere with certain characteristics (density, not-explosive, not corrosive, not filled with tiny grains of sand/silt, not hurricane winds). You could have different guns for different environments, but can quickly become awkward/inconvenient.
Stupid dragons. Guns pierce things. If your world is populated by lots of things that aren't seriously wounded by piercing (things with lots of armor, things with few vital organs, things that will slaughter you before bleeding out, etc) then it may be better to have a weapon that's capable of defense and easier to tie to secondary effects (poison, electrocution, fire, etc).
Stupid people. If you're living in a densely populated world (think Tokyo x10 with flying cars), then you're unlikely to ever have a clear shot. Combine that with possibly draconian laws about injuring innocents and it will encourage a more intimate form of assassination.
Stupid dome. If you're living in a place where a stray bullet can cause explosive decompression, then you might not want to use guns. And people around you will definitely not want you to use guns.
A common trope in science fiction is personal force fields/force shields that repel objects on the basis of their momentum/velocity, i.e. a high-velocity object (bullet) will be repelled, but a slower object (sword, knife, etc.) can penetrate. See e.g. Stargate SG-1 (where Colonel O'Neill regularly gets past Goa'uld personal force shields by throwing his knife) and Dune (where fighters are trained in a strange(-to-us) form of hand-to-hand combat that emphasizes quick evasions and defenses but slow attacks to push through the shield).
If these are cheap and/or common enough to fit your soldiers with, people are going to ditch the guns pretty quickly and rely instead upon hand-to-hand weapons that bypass these defenses.
Addendum: It should be noted that when the "higher momentum" of a bullet is cited as being the cause of the shield repelling it but not, say, a sword, it's just flat wrong. An average (medieval) sword (~3 lbs) with an average speed at impact (~40 mph) has around 25 kg-m/s momentum; a 115-grain bullet traveling at 1500 fps (a reasonably powerful handgun), however, has a measly 3 kg-m/s. That is, the sword has more than 8 times the momentum of the bullet! This could be why the sword can bypass the force shield though -- it simply has enough momentum to overpower the shield. (If this is the reason, though, cue the onslaught of high-caliber, high-velocity rifles and high-velocity shotgun shells as a possible countermeasure; you'd have to crunch the numbers to find what mass/velocity is needed for a bullet or slug to overpower the shield, and of course if it can be countered by high momentum sheer volume of bullets could likely be enough to overpower it.) Of course, a bullet likely does have more momentum than a thrown knife, so it could still be that the shield repels high-momentum objects -- but just make sure that you use the right terminology to explain why [foiled weapon] doesn't work but [favored weapon] does!
Another common excuse for hand-to-hand weapons goes something like this: "If you fire your gun you'll pierce the hull and kill us all!" This ignores, however, that modern technology has things called "frangible bullets" that, while not perfect, are designed to penetrate soft flesh but break apart harmlessly on firm walls/bulkheads; naturally, if piercing bulkheads in a pressurized spaceship was a real concern, this area of technology would advance quickly to give you useful firearms with minimal risk of depressurizing your spaceship. There's also a slew of non-lethal projectiles, from rubber bullets to beanbag rounds to Tazer rounds, that could be useful anti-personnel ammunition with, again, minimal risk to bulkheads.
Of course, with these types of rounds simple body armor now becomes a lot more useful precisely because of the desired properties of these ammunition types to not pierce hard objects, but they are still useful especially in situations where wearing body armor would raise suspicions and draw attention long before any shooting became necessary (e.g. walking through the spaceport to board the passenger liner).
Don't forget water.
Guns don't work very well under water. If you had a setting where the intelligent beings lived on a planet with little landmass, they might simply live under water. Either they are native water-dwellers, or they live in pressurized bases. You wouldn't really want to fire a gun in the base (less fun than firing it in an airplane), and in the water, they'd be mostly useless.
Looking at modern underwater weapons, they are more inline with old-school crossbows, with all that entails - relatively low ammo supply and fire rate among others.
As a bonus, underwater environment is much more 3D than our experience. It's harder to find useful cover, and you need to guard yourself from many more sides in a fight.
The combat might overall be more akin to the Roman legions - throw your spears (fire your spear-guns), close in quickly and battle up close. Shields and armour would probably be worthwile, and swimming head-on on enemies presents a much smaller are to hit.
The close combat itself would also be very different. You wouldn't be able to use broad slices you see in hollywood fencing, instead, you'd mostly concentrate on getting a good grip on your opponent (for leverage), and using short, mostly stabbing weapons. Leverage is very important, because you don't have the ground to push, so without a grip, you're not likely to do much damage. This might be offset by having small dart-guns for close combat when you can't get the leverage - if the opponent tries to avoid the meelee, you'd simply take out your dart gun, and give him a shot from close range. To prevent that, the opponent would likely rather fight with a grip.
Stab, stab, stab, stabbity, stab!
"Bullets don't worry much any more. Not since I had my brain enhanced to run at fifty times normal speed. What you think of as a second seems like almost a minute to me. So bullets... they're slow pokes. When I see them coming, I just get outta the way."
The cyborg pauses for a moment, taking a deep breath while his hands continue their amazing dance of juggling a dollar's worth of pennies, all at the same time.
"No, bullets don't scare me. I save my fear for really dangerous things, like someone as fast as I am but wielding a rapier or a knife."
If you want people commonly using guns, go ahead and do so. But remember that a knife beats a gun if the knife weilder is within 21 feet (6ish meters). Military personel commonly carry knifes with them even with automatic weapons as their main killing tool.
If you don't want the gun to dominate at greater distances, you have two easy options. Lots of obstructions or hazards. Obstructions are covered in other answers, so here are some hazards:
- The vacuum of space. If you are inside a ship and you pierce the hull, then it's game over for your victim, but you as well and anyone else on board.
- Innocent lives. Even the best marksman sometimes shoots straight through his target into whatever is behind it.
- Explosives. I know this Video Game and TV trope of setting off explosives with a bullet is total bull, but it is commonly believed total bull. Do like in Pamplona and run with the bull.
Additionally, swords could have a ceremonial significance like the samurai did in Japan. Ranged weapons were quite common in his time, but the katana ruled.
Lastly the Dune series of books had a personal force field that was stronger the faster the incoming projectile, so bullets would bounce off, but knifes would go straight through. There are potential real world armors incorporating non-newtonian fluids which would have a similar effect.
Obscured vision. If you often can't see very far away, then a melee weapon may be better than a ranged weapon. This could be anything that makes it hard to see very far away, such as dust or gas in the atmosphere, lots of fog, smoke, etc. It could also be a common countermeasure. I.e. if some technology makes it easy to produce lots of gas/smoke/vapor intentionally designed to block targeting sensors as well as human vision, it could make melee weapons very useful. Especially if it can overcome countermeasures people might come up with such as powerful fans or air cleansers.
Blocked line of sight/fire. There may often be many obstacles in the way of taking long-range shots (but not too much to make it hard to use a sword). In such cases, melee weapons may be better than ranged weapons.
Delicate environments where you can't afford to miss with a ranged weapon. Combined with adequate armor that means people need to use high-powered weapons, which would also cause too much collateral damage if they miss (like breaking environmental seals while on a spaceship, dome on a planet with deadly atmosphere, someplace with lots of volatile or very valuable objects, etc.).
Somewhere where ranged weapons would be detected and responded to by something whose attention you really do not want, and neither does your opponent. Setting-specific, but there may be detectors that will pick up ranged weapons but not melee weapons, and such weapons may attract a worse adversary than the people you want to fight.
The ranged weapons are ineffective for some reason. This is harder to find a reason for at high tech levels without using handwavium. At the tech levels where melee weapons were mainly used, not so much: armor and shields can be effective against arrows. Good high-tech armor or shields might deflect most ranged attacks, while for some reason there might be more powerful melee weapons... or the missile-deflecting shields might have a minimum radius, so one needs to advance inside the shield to hurt someone, at which point a melee weapon could be more effective.
i'll add one just for the shake of it.
You may want to learn close-combat / sword instead of firearm if you're not sure of the effectiveness of the firearm in a multiple environments.
- In the books "9 princes of Amber", the heros and it familly may go from dimension to dimension in a pinch. A sword can hit anywhere, a firearm need some given physics to work. Thus they learn sword (in fact, in their world, powder do not work).
- You have the same idea in the game "Arcanum", where the use of (any) magic slightly modify the standard physic around, and may cause a gun to fail.
In short : a sword works nearly everywhere, not a gun.
I can come up with two things off the top of my head.
The first, is very effective body armor, that negates projectile weapons, however for a sword to be viable, it would have to be more like a light saber or some kind of special edge high frequency sonics? or something similar.
The other could be where there are weird atmospheric affects where the atmosphere acts like a lens distorting things more than a handful of steps away so you don't know where you are really aiming at. So up close and personal it is.
ETA One more!
I just finished a book where an overseeing computer (or any other powerful being) allowed or disallowed different levels of technology in specific areas. So if a gun just wouldn't work, then...
I noticed most people forgot about the social part of the question so I thought I would address it. Here are a few social reasons to use melee instead of guns:
Some historical event may have happened because of or involving firearms. Such an event may have caused guns to be untrustworthy or just plain rude, maybe even illegal. Imagine guns are now looked down upon, and people give you disgusted stares if you have one. You pass a cop who sees it then arrests you. In a world like this, having a gun would be very hard to get and altogether not worth the hassle. Guns would also draw unwanted attention. People who use guns in this world are as bad as terrorists in America; they may not have been the ones who bombed the Twin Towers, but they might as well be.
Guns are for the few:
This could be in a culture where only certain people are allowed guns, such as royalty, or guns are very expensive. Maybe the only people allowed guns had to be specially presented them. This may include ceremonies similar to how the Queen knights someone.
In both of these examples, anyone with disregard for the law may still e able to get ahold of a gun, but this may prove difficult as the demand for guns will have gone down, leading to a near stop in production. On the flip-side, melee weapons will have become the most viable means of self defense, leading to a rocket in production.
I thought of another one that didn't involve the social environment:
- Concealment Certain melee weapons may be much more easily concealed than most guns. In addition, most melee weapons are flatter than guns, making them easier to slip up a sleeve or pant leg. (Note: This can work with number 1 if all weapons are made illegal.)
This option is pretty strait forward. A sufficiently isolated nation (meaning it wont be invaded and conquered by another nation that does use firearms) could have a social taboo against firearms. Most likely this would be a "honor" type scenario where killing someone without them having a chance to fight back is dishonorable.
Stick with a past timeline where firearms have not yet been developed
Components for the effective creation of firearms, or the creation of ammunition could be in short supply. This has a whole host of other implications on society as the components for fire arms are used in a huge number of different items.
You could also have an area that is craggy or heavily treed where that range of firearms is irrelevant because you can only get line of sight on your enemies when they are about to cut you in half. (This would be more feasible with early firearms as it took more time to reload).
If ranged weapons advance beyond solid shot, so lasers or something similar (think star wars), effective personal shielding against energy weapons could re-assert the value of melee combat. Similarly, advanced body armors could provide this protection the difference with traditional weapons is you have the velocity of projectile impacting with such force that even when it doesn't penetrate the armor it could kill the wearer from blunt force trauma and being knocked backward alone.
Wasn't sure where to place this. Specialized forces, think a modern special forces/ninja hybrid, could make effective use of blades. Blades are quiet and stealthy. A secret assassins guild could also use blades to maintain a mystique and fear factor. "We are so good we don't even need guns! COWER!!!!"
Guns depend on precise chemical reactions; too much or too little will be at least less effective and possibly break the receiver. So what if there's a process that can either destabilize or suppress chemical reactions? It could be simply "magic," or a psychic power, or ultratech. So in this world, an elite fraction of each army is composed of alchemical sorcerers/psykers who can blow up the other side's guns. Or maybe a Oxygenation Suppression Ray is part of every 22nd-century infantryman's kit.
Without guns, you can use bows, crossbows, and melee weapons. But armor renders most bows fairly ineffective (let's say), plus they're hard to use. You might have groups of master longbowmen, but they're not practical for widespread use.
Crossbows are great, but big and clumsy. They replace machineguns as defensive and suppressive weapons, but the rate of fire means that enemy swordsmen can close the distance and engage before you can reliably take them all out. So again you probably have units of crossbowmen, maybe even every soldier carries one, but they're not the alpha and omega of weaponry.
Finally, guns may still exist, but in niches. Snipers may still operate, but they have to shoot-and-scoot damn fast so they don't get zapped. Suicide soldiers may carry concealed submachineguns or similar, whip them out at close range, and try to inflict some damage before their own ammo kills them (or their guns simply jam, depending on the anti-chemical field).
You could say that the anti-reaction effect has a similar disruption on engines, thus eliminating vehicles, or perhaps diesel engines are too simple and rugged to be affected - it's up to you. Maybe even living things are affected! We're just a bundle of chemical reactions, so being subjected to this field could cause... shortness of breath; blurred vision; nausea; cancer; blind rage; psychic powers. Maybe only people with superb physical fitness can cope, so wars are fought with small groups of He-men. Or maybe women tolerate it better and they are the new warrior class.
Voila, a world where melee weapons are at least viable, if not the exclusive armament!
My answer is based on both conceptual but experience in martial arts and in RL situations:
"A gun pointed at your head, from behind or front"
The classic situation where a gun pointed at an individual, is a waste of time is if that individual is already close and not seen as a threat. Now lets remember modern warfare and policing is often against unarmed or lesser armed civilians. In these situations "A gun pointed at your head, from behind or front" can been easily removed and the gun bearer dropped - many Aikido techniques are based on this.
So this is based on the concept of you not being a threat being unarmed.
Bringing this in the OP ideas, if you could fool and drastically reduce your image of being as a hostile target, a classic disguise or a worn hologram of an old women or something else (donkey). Projected imagery, perception influence is a technology tool that some ex-govt scientist have worked on - remote influencing on a high level.
Line of sight
Many martial arts and gun users, cannot deal with someone behind them. Once again Aikido and other grappling art forms, you can drop another if you are next to them or behind them. Even if they have a sword or a gun.
Once again this is based on getting close.
In classic sword work, you are moving off line whilst striking or doing a lunge jab to hit between the ribs, this is followed through in Aikido where you are moving offline and into the attackers space. Even taking classic wrist slices, which happen a lot in Samurai cultural (hence the armor over both sides of the wrists), you just need a well aimed slice at the wrist - easy over 4-5m.
I have seen Sensei's and other Aiki's doing massive 8m or more flying forward rolls, holding a Boken (wooden sword), clearing a whole dojo matt in one leap, counting the roll at the end. I used to be able to do sideways Aikido rolls. Considering part of the training is to chain various directions of rolls, you could easily use obstacles and more to get out of the field of vision of an armed attacker.
Bringing this into a sci-fi situation if they gun bearing is distracted or has a false target, a hologram perhaps, then you can get behind them.
Not being seen
Nothing too technology based here, but reading into Ninjutsu how they hid was often quite cool and simple. From flashing light off their blades to momentarily blind the opponent then moving out of view. To staying outside of the peripheral vision when approaching someone. And simply being really quick and good at hiding, awareness of shadows and more. A classic stealth situation.
If you take this into a science fiction era, we already have had publically exposed light wrapping tech and light absorbing technology - nanotech black that absorb 100% of the light, its used in those new space bound telescopes. Plus the stealth tech in the military..
That might add to above.
If you have a cultural honor system where duels can occur within the battlefield, swords or other melee pieces can be quite practical. Take the encounter between Fin and Tr-8r in The Force Awakes, but add a cultural honor rule that would prevent Han Solo's intervention. Boom! Melee combat is not the main form of combat, but in large face-to-face battles, it may be more preferred. That and upper body armor will allow people to be close enough for a duel to be the most practical combat.
Not sure if this qualifies as a comment or an answer, but here is something to think about. A Firearm can be detected from a variety of methods. Dogs can smell the propellant, Metal detectors can sense the projectile, the frame, the barrel and the cartridge. Can you get your firearm to where it needs to be in order to use it. In a covert situation, the answer is "with great difficulty"
A martial artist, however, is the weapon. More particularly, a ceramic bladed knife will not be detected by normal methods and can penetrate modern body armor anywhere there isn't a shock plate.
I get that this deals more with covert operations, but this can grow out to maybe warfare status when you consider that power being brought to a point may be more effective than bludgeoning the countryside. A number of assassins that get inside and take out 20 or so top level leaders could potentially disrupt a war effort enough to bring it to an end.
Okay you guys gotta go to guerilla school.
Guns almost invariably make either loud noise or bright lights (heat beams excepted). Granted if you want stealth you could go with silencer or suppressor for your chemical slug thrower. Each of these possibility and their variations also have a strong chance of hitting that 10,000 volt liquid hydrogen line or disrupting anti matter exchange unit (I speak in simile).
However you can achieve little noise / flash with your good old buddy the knife. But there are other bonuses to be found here: shooting someone in the gut and tying up two members of a boarding team (one to treat one to guard -- a similar tactic pursued by the North Vietnamese. Again the knife can do this only with more precision. Its easier to cut someones larynx with a blade.
Ye old armor argument. Space suits can deflect / absorb the incoming projectiles energy. Kromey says swords are better than bullets. I don't have time to work this out, but I have heard a space suit can take a full sized .50 caliber round (I have no source, so take it for its worth). The point is that when we last saw these style argument was the middle ages and we worked out weapons like eared daggers (https://en.wikipedia.org/wiki/Ear_dagger) and misericordes (https://en.wikipedia.org/wiki/Misericorde_(weapon)). The latter was by the doctors of the day to mercifully kill warriors with a quick jab through the armpit to to the hear. It was intended for use on those who would die slow horrible deaths. The point being that no armor is full proof and it's generally easier to hit that seam, overlap, what have you with a blade.
Finally knives allow a different type of warfare. Sure you could pistol whip or blow the lower jaw off an adversary, but with a knife you do all kinds of horrible things. Cut his fingers of and sew them to where his genital were. Stuff his cut off toe into his mouth. The list goes on. Try and do this with against a 10 man squad and you'll end up another fighting another 7 or 9. Oddly enough if you do this to say 2 or 3 men out of a 10 man crew someone is going to loose their proverbial apple pie. A disorganized enemy is always easier to fight than a organized one.
Bonus points: Change the dagger to a wasp injection knife (http://waspinjection.com/) -- it injects gas into a deep stab wound. But we will go one better: Mix the gas white phosphorous powder and nitrogen. Make the guy scream as the medic probes the wound.
Sword is capable of piercing a kevlar coz only high speed contact can harden it Try to explain. Kevlar can stop the bullet coz of ripples effect that the bullet impact cause(not sure about it). So we somehow have there small(~5 cm) round of fabric that,still holdin a flat(in compare of spike-like) state, moves with the bullet for a while.Sword will just go straight through .