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?
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.
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.