Module 2 Lesson 3 Challenge

Hey,

I got about 80% of the way with this challenge but couldn’t quite get over the random number & adding item to the array. I’ve downloaded the solution but wonder if somebody could walk me through in plain English what is going on here?

let randIndex = Int.random(in: 1...array.count-1)

Thanks!

Jez

@jeremyjameslevy

You will have noticed that the array has 5 elements and you will also recall that the lesson on arrays makes the point that the positions of the array elements starts at 0. So if you have 5 elements in the array then the positions are 0, 1, 2, 3 and 4.

That line of code is generating a random number in the range of 1 through to the length of the array.

NOTE: that line of code should be as follows otherwise the first element (the Apple) will never be used:
let randIndex = Int.random(in: 0...array.count-1)

Breaking it down.
random() is a function available to generate a random number in a range specified so in this case the range is 0 through to the array.count minus 1 ie, 0...array.count-1
array.count will return 5 and given that the first position in an array is 0 then 1 needs to be subtracted from the count so that you do not exceed the array scope. The last element position in this case is 4.

I hope this is making sense.

Great, thanks Chris. That was very helpful & Chris does actually explain it in the following lesson too.

Hi. Just a quick question on which is a better option, the code the solution used in the button action:

let randIndex = Int.random(in: 0...array.count-1)
 items.append(array[randIndex])

Or the following code.

if let wordArray = wordArray.randomElement() {
                    wordList.append(contentsOf: [wordArray])
                }

Is it just a matter of personal choice or is one a more suitable choice. Thanks.

Both ways work although for clarity and simplicity I would write the second code segment like this:

if let word = wordArray.randomElement() {
    wordList.append(word)
}

You are getting one word out of wordArray so use the let constant in the singular tense. Given that it is one element then you can append that in the singular as well which means there is no need for the parameter contentsOf: which is where you are appending an array to an array.

1 Like

Great. Thanks for the advice.