This paper presents a novel approach to enhance both the diversity and quality of images generated by Generative Adversarial Networks (GANs). Instead of employing random selection, we optimize the length of the latent space ( \(\vec {{\textbf {z}}}-dimension\) ) using swarm intelligence. To achieve this, we use the Dispersive Fly Optimization (DFO) algorithm, which is inspired by the natural foraging behavior of flies searching for food within their environment. In our implementation, the DFO algorithm iteratively adjusts the \(\vec {{\textbf {z}}}-dimensions\) based on the best performing solutions, determined by the fitness function of the Inception Score (IS). During each iteration, the "flies" (representing \(\vec {{\textbf {z}}}-dimensions\) ) modify their positions according to the optimal configuration \(\vec {{\textbf {z}}}-dimension\) discovered in the previous iteration. The Inception Score serves as our primary metric for evaluating the quality and diversity of the generated images. We conducted experiments using the MNIST dataset to validate our approach. The results demonstrate that employing swarm intelligence methods to optimize \(\vec {{\textbf {z}}}-dimension\) improves both image quality and diversity compared to traditional random selection methods. In this repository (https://github.com/AREEG94FAHAD/DFO-GAN), you can find the fully implemented code.