Since magnesium is located in group 2 of the periodic table, it will have 2 valence electrons. This means that magnesium can easily lose those electrons to become stable, i.e. to have a complete octet.
When that happens, the magnesium cation, a positively charged ion, is formed
Likewise, potassium is located in group 1, which means it has 1 valence electron. When it manages to lose that electron, it will form the potassium cation, or
On the other hand, iodine is located in group 17 (main group 7), which means it has 7 valence electrons. It is easier for iodine to gain an electron rather than to lose 7, so it will form an anion, or negatively charged ion,
This means that the ionic compounds formed with these two cations and the iodide cation will be
Here is a video which discusses how ions form and how to determine their charges.
Video from: Noel Pauller