I’m printing out a random element from dictionary I created
I want a variable to be in the middle of the key and it’s paired value
Dictonary1.randomElement()!.key + "(variable1)" + Dictonary1.randomElement()!.value
Clearly this doesn’t work because it prints a second random value from the dictionary rather than the original key’s pair.
I’m having trouble finding the proper syntax for a function like this and I can’t find any examples.
3
Answers
Store the
randomElement
in a variable and then access it’skey
andvalue
members:Your code generates as you said two different random values as you call the randomElement() function twice. To use the same value both before and after the variable, you would have to store the randomElement() in a variable and replacing the randomElement() call with the variable. When assigning it to a variable, it will only be called upon initialization of the variable, and the value of the variable will therefore stay the same so that you can use the same variable multiple times.
You can print this using a
flatMap
on the result fromrandomElement()