How to swap class for drupal 8 services

One of the reasons we are using services instead of plain classes is possibility to swap out class that each service uses.  So what we need to do is we need to create a new class that's overriding an existing service class, and then we need to alter the service container to use our new class. To find examples how to do that, search codebase to find this "extends ServiceProviderBase" so we are looking for classes that extend ServiceProviderBase  and how is it used. First this needs to be a class in /src folder so it is autoloaded and if you want this service alteration to be recognized automatically, the name of this class is required to be a CamelCase version of your module's machine name followed by ServiceProvider (example below is then TokenServiceProvider.php file), then it needs to have an alter function that will change the class we want to use. 

/**
 * Replace core's token service with our own.
 */
class TokenServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('token');
    $definition->setClass('\Drupal\token\Token');
  }
}

one of the simplest examples you can find in contrib token module, where it is using alter function to first find proper definition of service in container and then to set a new class for this service, clear cache and this will work.

For more advanced usage of this you can check d.org docs https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services

Also check out service decorators as they might be more useful, depending on the use case
https://www.axelerant.com/resources/team-blog/drupal-8-service-decorators