dimanche 27 août 2017

Randomly selecting an object from an Array without it repeating objects in a row without removing

I'm new to swift and have tried various ways to get this to work

I have an object of arrays that were created inside the viewController inside the viewDidLoad() method. There are 5 objects inside.

var objectss: [CustomClass] = [] // Five objects are created inside viewDidLoad() and added to this array

Each objectss index starts from 0 to 4

I have a IBAction button that randomly chooses one of the objects inside the Class Array

Also I will note that each object has a button (Meaning I have 6 buttons on the view controller with a tag to each starting from 0 and incrementing to 5)

So to explain why there is 5 instead of stopping at 4 is that I've hooked up these buttons into one IBAction and used a switch that has two cases. First case is 0, 1, 2, 3, 4 and assigns the Class variable reference created on top to equal objectss[sender.tag] so if the user clicks on the first button (tag = 0) it will display the object's information at index 0 (inside the array) to display in the next secondViewController

The second case is 5 which is the random button that randomly gets an object from inside the array and displays that object's information onto the next secondViewController

So I hope that makes sense that I am using the sender.tag to determine which button is being pressed.

Inside the @IBAction I've done this:

switch sender.tag {
    case 0, 1, 2, 3, 4:
         objectSelected = objectss[sender.tag]
    case 5:
        let index = Int(arc4random_uniform(4))
        var random: Int
        repeat{
            random = Int(arc4random_uniform(4))
        } while index == random

        objectSelected = objectss[random]
    default:
        break
 }

I tried to do it this way to stop getting the same object in a row, but it still does it and sometimes takes forever to display some of the other objects in the secondViewController.

I've also already tried

let index = Int(arc4random_uniform(UInt32(objectss.count)))
objectSelected = objectss[index]

But that kept showing the same object in a row a lot of times




Aucun commentaire:

Enregistrer un commentaire