Random Swift, Part 2

How to generate random text, email & color

Sebastian Kreutzberger
6 min readAug 12, 2015

In Part 1 I introduced you to the main randomizing functions in Swift. In this article we will now use these functions to randomly generate some more complex data which work great if you need to test fake user input in a UITextView, UILabel or CGRect:

  1. a random text of a defined length consisting of digits, letters & spaces
  2. a random email address
  3. a random color (a UIColor() to be more specific)

As always, I strongly recommend to try all code inside an Xcode Playground.

Random Text

To get basic randomized text you need to deal with the building blocks of text called characters. A character can be either a digit (0–9), or a letter (a-z) or a symbol (!?§$%&/=) and can also be a the space character (the blank character which devides words from each other).

For random text you now just need to generate some of these random character and put one after the other (called concatenation).

Random text generated in that way could look like the following line: WJ7c3kZ7SFHj3 9ow33iZA 8n 4AVa69Xh2t UKx3tNfJGfs N

… ok, it is maybe a language with a lot of digits but it has all ingredients of text, it has character of all kind in a random distribution.

You may now ask yourself how you would get a random character and the solution is by randomizing its character decimal value.

A character’s decimal value is a number and each character has its own number. The best is that similar characters (like all digits or all lowercase characters) are in a defined range of numbers. For example the uppercase characters of the alphabet have the following decimal values:

  • character “A” has decimal value 65
  • character “B” has decimal value 66
  • character “C” has decimal value 67
  • character “D” has decimal value 68
  • character “E” has decimal value 69
  • … and so on …
  • character “Z” has decimal value 90

You can use now that knowledge to get a random uppercase character by generating a random number within the range of the lowest decimal value 65 (for an “A”) and the highest decimal value 90 (for a “Z”).

And the same works for digits (decimal values from 48 to 57), lowercase characters (decimal values from 97 to 122) and the space character (decimal value 32). As hint, you can get an overview of the most important English character decimal values at an ASCII table like this one:

ASCII Table

ASCII Table showing Decimal value of a character (plus a hex value which you can ignore)

If all goes well then you have now generated your random random decimal number which you just need to turn into a character (“A”, “z”, …) by using the Swift statement String(UnicodeScalar(yourDecValue)). As last step just concatenate each newly generated character to get the final text (in Swift a text is called a String).

Before it is getting too theoretical please see my function to generate random text. I also added the randomization of the character type and added an optional parameter ‘justLowerCase’ which we will need further down below:

When you paste the function into a Playground then you can get results like the following (of course the generated texts will be different because they are random):

Screemshot of my Playground where I test the function with different text lengths. The random text is in the right column.

You can now use the randomText() function to generate all kinds of texts. And if you set the optional parameter ‘justLowerCase’ to true then you can even generate just lowercase words without spaces or digits!

Exactly these randomized lowercase words we will use to generate a random email address.

Random Email Address

The format of an email is well-defined. To keep it simple we can say that each email consists of the following parts (in reality it can be more complex):

A word which can contain digits a dot & English alphabet characters
+
an @ symbol
+
another word
+
a . (dot)
+
a domain suffix which is a collection of defined character combinations (for example com, net, org, io, co.uk)

Here are some example emails which show the variation in the elements:

  • peter.smith@ibm.com
  • hearty1234@love.fr
  • me@google.co.uk

Long story short, let’s use the randomText() function with the parameter ‘justLowerCase’ = true to generate the word in front of the @ and the word after the @. The domain suffix we pick randomly from a list of suffices. It will not contain numbers or dots but that should not matter for now:

After I pasted that function into an Xcode Playground and called several times I got the following random emails address:

Screenshot of my Playground. The randomly generated email addresses are in the right column.

Great, isn’t it?

Random Color

It is always good to be able to randomly generate some colors, for example as background colors of animated objects or views.

In Swift, a color is made / defined by:

a mixture of some Red + some Green + some Blue

All 3 values (red, green, blue) are float values within the range of 0.0 (means: do not put that color in the mix) and 1.0 (means: put a lot of that color into the mix).

Additionally, a color also contains of an alpha value which sets the transparency of the color. An alpha of 0 means full transparency (the color becomes invisible) and 1 which means no transparency at all.

To generate a random color you just need to generate random values for red, green and blue in the range of 0.0 and 1.0 by using Swift’s drand48() function.

Since it is really so simple I right away show the function to generate a random color (UIColor) which can be right away used with other Swift UIView objects and subclasses of UIView:

Let’s again try that in our Playground. We draw a rectangle and set its background color to randomly generated colors.

Good to know: to actually see a created UIView object, like our rectangle, in a Playground you need to click on the + icon in the right column (next to the eye icon) of the source code line.

Screenshot of my Playground with a rectangle and its ranomly generated background colors.

Wow, there are so many colors!

Random Integer within Range

But wait, if you are still with me then I have a small extra for you. It is a function which generates a random integer within a given range. It hides the strange looking randomizing function arc4random_uniform() and the UInt32 type:

And the Playground as proof:

Screenshot of my Playground. Results are in the right column.

I know, that was a lot and it’s great that you made it until here! If you want to dive deeper into understanding randomizing in Swift then you could for example use the randomInt() function inside the randomText() function at the beginning of the article.

An additional “homework” could be also to extend a type like Int or CGFloat with a random() function. Here is an example as starting point for an Integer extension. Just put it in a file in your project and then you can generate random Ints by calling Int.random(maxValue)

I would love to get your feedback, and please don’t be shy and heart or share the article if it was helpful or interesting for you. Thanks!

--

--

Sebastian Kreutzberger

Creator of SwiftyBeaver, Co-founder & CTO at YGO. Prior CTO / CEO / founder of several VC-backed companies, including Wunderlist & RhodeCode.