I have a very confusing situation that I can't figure out. I'm not quite fluid in swift so please bear with me if this is a rookie mistake.
So let's say I have a variable x
let number = Int.random(in: 0 ... 5)
x = number
let number2 = Int.random(in: 0 ... 5)
y = number2
ok, so establishing that x is a random integer from 0 to 5 if I'm not correct, which means it's 6 values
Also, we have this array
let arrayValues = ["apples", "bannanas", "cherry", "date", "eggplant", "dorito"]
Here we can begin with the situation, I will include some of the steps I have attempted.
So I want to have x, let's say in this case the computer chooses a 3, and y is 5.
Keep in mind that every time the program runs, it will provide a different number.
What I want to do, is to match those x and y values with the indexes of the array "arrayValue".
In this example, x = 3 and y = 5
therefore if we compare the index of the array "arrayValues", with the x and y that would be
"date", (the index would be 3 which is equal to x )and "dorito" (the index is 5, which is equal to y).
However, here's the problem, how do I do this? Because the values are changing every time, I also can't use arrayValue.contain to find the value. due to the fact, the numbers aren't strings. As well as the fact if we convert the numbers into strings it would be pointless again, because it would be searching for "x", and not searching for the actual value of x.
Is there a code to fix this?
Thanks in advance.
You cannot set a string to a var (x or y) defined as Int.
What you have simply to do:
- generate a random number x
var x: Int = Int.random(in: 0 ... 5)
- use this x to get the string value from array
let arrayValues = ["apples", "bannanas", "cherry", "date", "eggplant", "dorito"]
var xString = arrayValues[x]
Now on, use xString and not x to refer to the selected object.
Note: no need to use enumerated here, arrays are ordered, that's enough here.
A more direct way to do it is to call random directly on the array:
let arrayValues = ["apples", "bannanas", "cherry", "date", "eggplant", "dorito"]
let x = arrayValues.randomElement() ?? ""
print(x)