Home > Blockchain >  Image Literals, Arrays and randomizing in Swift. Why does this method work but the other doesn'
Image Literals, Arrays and randomizing in Swift. Why does this method work but the other doesn'

Time:10-09

Creating a dice roll app following Angela Yu's App Brewery bootcamp on Udemy. She uses image literals but those seem to have been deprecated on newer versions of Xcode.

I get the error: Cannot assign value of type 'UIImage??' to type 'UIImage?' Whenever I try to use diceArray.randomElement()

However, diceArray[Int.random(in:0...5] seems to work fine. My suspicion is maybe to use .randomElement() I need to use imageView but new to Swift so not sure if this is correct or what the difference even is. Any explanation would be appreciated. Thanks.

      @IBAction func rollButtonPressed(_ sender: UIButton) {
            
            
           var diceArray = [UIImage(named: "DiceOne"),UIImage(named: "DiceTwo"),UIImage(named: "DiceThree"),UIImage(named:"DiceFour"),UIImage(named:"DiceFive"),UIImage(named:"DiceSix")]
           
            diceImageView1.image = diceArray.randomElement()
            diceImageView2.image = diceArray[Int.random(in: 0...5)]
          
            
        }

CodePudding user response:

UIImage(named: initializer returns UIImage? and randomElement returns an Optional so it's ?? , you can force it

diceImageView1.image = diceArray.randomElement()!

CodePudding user response:

As Sh_Khan pointed out, you have an array of Optionals since UIImage.named(_:) returns an Optional.

I would suggest adding a call to compactMap at the end of your code that declares your array of images:

var diceArray = [UIImage(named: "DiceOne")…].compactMap { $0 }

That will make diceArray an array of UIImages instead of Optional(UIImage) (and strip out any failed attempts to load images.)

  • Related