I'm trying to retrieve and display from a dictionary a randomised set of an image with its associated text on click of a button.
First, I tried having the image array and text array seperate and use Int(arc4random_uniform()) to randomly pick the elements from the array to display. It worked, BUT in doing so I need to make sure the image and its associated text are in the same position within their own array and I thought there must be better ways to structure the data by combining them into a multidimensional array or a dictionary. I end up using a dictionary, but got stuck don't know how to get the image and text to display.
See in the code below //THIS IS THE BIT I GOT STUCK AT. I don't know how to retrieve the image and its text from the dictionary.
I am not sure if it's ok to put the myImage and myText var in the dictionary and it seems a bit tedious to keep repeating 'myImage', 'myText' for each set as well.
@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myText: = UILabel()
var randomSet = [[myImage:"1-image", myText:"text for 1"], [myImage:"2-image", myText:"text for 2"], [myImage:"3-image", myText:"text for 3"], [myImage:"4-image", myText:"text for 4"], [myImage:"5-image", myText:"text for 5"]]
func randomiseSet (){
let randomNumber:Int = Int(arc4random_uniform(5))
//THIS IS THE BIT I GOT STUCK AT
myImage.image = UIImage(named: randomSet[randomNumber])
myText.text = randomSet[randomNumber]
//END
}
@IBAction func showRandomSet(_ sender: UIButton) {
randomiseSet()
}
I also tried instead of using myImage.image = .... myText.text = ....
return randomSet[[randomNumber]]
Both didn't work and showed 'Build Failed'
I have also investigated using CoreData but I'm a noob and that opens another can of worm for me regarding binary data for images vs using URL due to image size etc.
Any suggestion on what's the best way to fix the above is much appreciated. Thanks.
The problem is that the line
myImage.image = UIImage(named: randomSet[randomNumber])
is wrong becauserandomSet[randomNumber]
returns[String:String]
, notString
. What you instead need to do israndomSet[randomNumber]["myImage"]
, which will return the string you want to initialize theUIImage
.Also note: your dictionary's keys should be
String
s in this case. UnlessmyImage
andmyText
are declared asString
s elsewhere, your dictionary is set up incorrectly. Try changing yourrandomSet
to[["myImage":"1-image", "myText":"text for 1"], ["myImage":"2-image", "myText":"text for 2"], ["myImage":"3-image", "myText":"text for 3"], ["myImage":"4-image", "myText":"text for 4"], ["myImage":"5-image", "myText":"text for 5"]]
So, implementing the changes, your code should look something like this: