Avoiding Magic Numbers

Ashley Oldham
2 min readApr 27, 2021

When I googled ‘magic numbers’ the first thing that popped up was the British pop band. But I’m afraid this is not what this post is about! I then specifically googled ‘magic numbers in swift’ and many questions popped up, so I thought this was a topic worth discussing. Although this isn’t specific to the Swift language, this post is relating to a swift application.

Firstly, what is a magic number, and why avoid them? A magic number is when you directly use a number (Int) in your code. Maybe the corner radius of a shape is set to 7.0. You may also have many of these scattered around different views and everything works, so it’s no big deal, right?

But what if your designer comes back to you and wants to change this radius to 12.0? You will need to search all lines of code to find and change each corner radius to the new desired value of 12.0. This can take up some valuable time, and you may miss one or two.

One way around this could be to use Variables that are used in place of the magic numbers.

In Swift, we could create a new file to store a place for these Variables. Enums are a great way to define and store a group of values.

example of enum

Now if we need to set our new cornerRadius value, we can adjust this in one place. When setting a new value that will use our constants, we can clearly define the numeric value by using the set constant. This will make it easier to read when the code is being read by another developer too. Providing we name our variables well of course!

example use of Constant variable

Thanks for reading! I hope this helps someone out there. It helps me to write things down so I understand them better.

--

--

Ashley Oldham

Career changer but still a problem solver. New to Code and blogging my experiences with it. Hoping this helps both you and I learn!