0

I'm trying to write my first app in swift on Xcode and I'm stuck!!

I have a dictionary - I've shuffled it - and now want to print the values to different labels in the order they have been shuffled in.

I'll give an example and try and explain the outcome I am expecting.

    label1 : UILabel! 

label2 : UILabel! label3 : UILabel! label4 : UILabel!

animals = [1:"cat", 2:"dog", 3:"snake", 4:"Mouse"]

shuffled animals = animals.Shuffled

// - expecting output like [2:"dog, 4:"mouse", 1:"cat", 3:"snake"

I tried... `Label1.text =shuffledanimals[0] Label2.text = shuffledAnimals[1] Label3.text = shuffledAnimals[2] Label4.text = shuffledAnimals[3]'

// like the index of the dictionary.. (this didn't work) not sure why??

Also is there a way to put this in a loop to make it cleaner ?

Any help will be appreciated .. Thanks

Please note.. I would like to use a dictionary over an array as I have other needs for the keys.. and it has 40 pairs in so my method is not practical at all

BC147
  • 15
  • 1

1 Answers1

0

In this example, you're using a dictionary, which is inherently unordered. So unlike arrays, where you can access information using indices like array[0] and array[1], dictionaries don't work the same way. No matter the order that you might be seeing the dictionary, whenever you access animals[1], it'll always be "cat" because that is "Cat"'s address in the dictionary.

There are a couple solutions for what you're trying to do. A quick and dirty way to do this is to create a second array (NOT a dictionary). Something like this:

let array : [Int] = [1,2,3,4]

Then, you can shuffle this array by doing something like:

array.shuffled()

Lastly, select a random dictionary piece by using the new (random) order of the array like this:

label1.text = animals[array[0]]

So long as you have the same numbers in array as you do as the first part of your animals dictionary, this will work just fine. But be careful to not accidentally add a number that isn't in animals, because that'll cause an error.

Alternatively, another solution is mentioned here that uses different and more advanced ways of declaring dictionaries:

Dictionary returns consecutive/shuffled values when iterating in swift

In terms of putting it into a loop, if you use the first option, you can do something like this:

for item in array {
    print(animals[array(item)]
}

this will call each of the items in the array, which will have been shuffled provided you have already called the .shuffled() function.

Jeff Cournoyer
  • 474
  • 2
  • 12
  • Thanks for your answer. I do need to keep the dictionary for other reasons but I understand your point... say I made an array of the animals in my dictionary is it then possible to use a loop to print to a different label each time it loops .. for example array = ["snake","car","dog","mouse"] so loop 1 will print snake to label1 and loop 2 will print car to label 2 etc .... thanks – BC147 Jan 16 '21 at 13:19