'How do I pass an array of images to a variable of type UIImageView in swift? Or what is the right way to store multiple images in a single array?

import UIKit

class ViewController: UIViewController {

/* Created IBOutlets for the dices on the Interface builder. */
@IBOutlet weak var diceImageView1: UIImageView!
@IBOutlet weak var diceImageView2: UIImageView!
    
override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func rollDiceButton(_ sender: UIButton) {
    diceImageView1.image = [UIImage(named: "DiceOne"), UIImage(named: "DiceTwo")]
 }
}

I want to pass a series of images to my diceImageView1 variable which is of type UIImageView but my code is not working. Any help will be appreciated. Thank you.



Solution 1:[1]

@IBAction func rollDiceButton(_ sender: UIButton) {
    diceImageView1.image = [UIImage(named: "DiceOne"), UIImage(named:   "DiceTwo")][1] // where 1 refers to the index, could be any number from 0
 }

I added an array index to the end of the array values and it worked fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gilles Ashley