skip to Main Content

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


  1. Store the randomElement in a variable and then access it’s key and value members:

    let dictionary1 = ["1":"Test1","2":"Test2","3":"Test3"]
    let variable1 = " = "
    
    if let randomElement = dictionary1.randomElement() {
        print(randomElement.key + variable1 + randomElement.value)
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. You can print this using a flatMap on the result from randomElement()

     dictionary1.randomElement().flatMap { print($0.key + variable1 + $0.value) }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search