Unlock This Episode
Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.
Introduction
Last week we discussed the topic of “Composable Randomness”, which seeks to understand how randomness can be made more composable by using function composition. We also compared this with Swift 4.2’s new randomness API, which arguably is not composable, in the sense that it is not built from units that stand on their own and combine to form new units.
We spent some time building up fun generators, like randomly sized arrays of random values and even random password generators, both of which are not easily expressible with Swift’s APIs.
Today we are going to take this a big step forward, and unlock the ability to create random values from any data type we define. We’re actually going to do this in two different ways:
We’ll do a bunch of upfront work with a Swift specific feature that unlocks the ability to effortlessly generate random values from any data type, but we’ll see it’s a little bit rigid.
Then we’ll try another approach by doing a very modest amount of upfront work to build up the tools to generate random values from any data type in a very flexible way, but it takes a lil more work to do than the first method.
So let’s start with the first method, and it begins by look in an unlikely place: the Decodable
Protocol.
Subscribe to Point-Free
Access this episode, plus all past and future episodes when you become a subscriber.
Already a subscriber? Log in
Exercises
We skipped over the
allKeys
property of theKeyedDecodingContainerProtocol
, but it’s what’s necessary to decode dictionaries of values. On initialization of theKeyedDecodingContainer
, generate a random number of randomCodingKey
s to populate this property.You’ll need to return
true
fromcontains(_ key: Key)
.Decode a few random dictionaries of various decodable keys and values. What are some of the limitations of decoding dictionaries?
Create a new
UnkeyedContainer
struct that conforms to theUnkeyedContainerProtocol
and return it from theunkeyedContainer()
method ofArbitraryDecoder
. As with theKeyedDecodingContainer
, you can delete the samedecode
methods and have them delegate to theSingleValueContainer
.The
count
property can be used to generate a randomly-sized container, whilecurrentIndex
andisAtEnd
can be used to let the decoder know how far along it is. Generate a randomcount
, default thecurrentIndex
to0
, and defineisAtEnd
as a computed property using these values. ThecurrentIndex
property should increment wheneversuperDecoder
is called.Decode a few random arrays of various decodable elements.