Topics

#285: Generating Random Data with RandomKit 🎲

Topics

Whether we need sample values while prototyping our app's interface, or some multipliers for our game's logic, random data can be incredibly useful when programming. Today we'll check out a great library from Nikolai Vazquez called RandomKit that makes generating random data both simple and intuitive. Let's begin.

RandomKit is built on a set of Swift Protocols. We're provided Random, RandomWithinRange, RandomToValue, and many more. RandomKit then extends a bunch of types to conform to these protocols.

(This is great because it means we can easily add RandomKit-style functionality to our own types, if we ever need to. Neat.)

Let's try out the basics. Some of the most common things to generate randomly are numbers and booleans. RandomKit has us well covered here, supporting all the major numerical Foundation types (and more):

Double.random() // 0.6472946529383645
Int.random(within: 1...10) // 7
NSNumber.random(within: -5...5)  // -3
CGFloat.random(0...1)  // 0.27969591675319
Bool.random() // false

Neat. Next up, Strings:

String.random(ofLength: 5) // "$-=5t"
Character.random() // "#"

We can also easily grab a random element from any Swift Sequence or Collection:

"Little Bites of Cocoa".characters.random // "o"
["Han", "Luke", "Chewie"].random // "Luke"
NSDictionary(dictionary: [ "firstName": "Han", "lastName": "Solo" ]).random // ("lastName", "Solo")

But wait, there's more! RandomKit is incredibly comprehensive. Let's try some more advanced functionality like Dates:

Date.random(within: Date.distantPast...Date())  // "Feb 7, 472, 5:40 AM"

URLs:

URL.random() // https://stackoverflow.com

...or even UIColors and NSColors:

UIColor.random(alpha: false)  

Last but not least, we can even grab random values for CoreGraphics types:

CGPoint.random(within: 0...50, 0...50) // {x 23.284 y 45.302 }
CGSize.random(within: 0...50, 0...50) // {w 29.475 h 12.863 }
CGRect.random() // {x 3.872  y 46.15  w 8.852  h 20.201}

These examples were just a (sorry) random-sampling of RandomKit's functionality. It has a ton more to offer.

Learn more about RandomKit at git.io/randomkit