Source: https://cryptomarketpool.com/how-to-swap-tokens-on-uniswap-using-a-smart-contract/

Swapping in DeFi

A decentralized world is a free world, one with minimal restrictions on how you manage your assets or what you transfer them into. Because it’s automated, Swapping is another method in DeFi for transferring assets.
A token swap is essentially a mechanism in which investors exchange their existing tokens for new ones.
Token swapping is only possible with a DeFi protocol, such as a decentralized exchange, which, unlike centralized exchanges, follow the method of AMM (automated market makers) wherein the smart contract code is designed in such a way to make token swapping possible. These exchanges are 'non-custodial' and rely on liquidity provided by users through yield farming or liquidity mining.
Because of decentralization, token swapping is solely governed by smart contracts. There is no requirement for input from the exchange, and there are no elements that could lead to human error.

DEX token swap vs CEX trading

A DeFi user wishes to exchange funds. He does so by logging into his digital wallet and connecting with the DEX to request a token swap. After processing the request, a smart contract pulls tokens from the digital wallet in exchange for the trader’s desired token.
The person in question did not have to:
  • Log in
  • Move funds to the exchange
  • Convert fiat into crypto beforehand
Moreover, since DEXs by design do not enforce Know-Your-Customer (KYC) parameters, your identity is almost completely anonymous. There are also no limits as to how much fiat value one can swap during a single day, which is a stark contrast compared to centralized exchange (CEX) withdrawal and deposit limits.
There are, of course, disadvantages as well. The cons include:
  • Liability: In a decentralized environment, all actions and their consequences are delegated to the user. If a trader executes a trade by mistake or transfers assets to the wrong address, it is entirely their fault. There is no form of technical support that can escalate and resolve the issue, which is almost always found on CEXs.
  • Security: Non-custodial wallets are primarily used when executing token swaps. They are fully managed by the owner, and all problems arising during trading have been explicitly caused by him. If the investor does not protect his wallet well, they risk losing all funds.
  • Fees: DEXs rely on the use of Automated Market Makers (AMMs) to pull and push liquidity. AMMs are essentially smart contracts, and every action performed requires a respective smart contract that consumes gas fees provided by the user. Gas fees are exceptionally expensive compared to the standard taker/maker fees imposed by traditional order-book-styled CEXs.