简体   繁体   中英

how to repopulate an array once items have been removed swift

I have an array and remove items so that they do not get repeated while calling elements from the array. However, once all elements are called I want to repopulate the array after OK is clicked on the alert. I can not figure out how to do this. Any ideas?

func select() {
    //random phrase
    if array.count > 0 {
        let Array = Int(arc4random_uniform(UInt32(array.count)))
        let randNum = array[Array]
        // random phrase when program starts
        self.phrase.text = (array[Array])
        //removing
        array.remove(at: Array)
        array.
    } else {
        let  alert = UIAlertController(title: "Completed", message: "Click below to reload datac", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "ok", style: .default, handler: nil))
        present(alert, animated: true)
    }
}

General psuedo code would be:

declare an array with items
invoke select() to choose a random item
    if array is empty 
        re-populate array after user prompt
        return
    end-if

    select random item and assign to phrase 
    remove item from array 
end select()

So something to the effect of:

var items = ["a", "b", "c"]
var phrase: String?

func selectRandomItem() {
    if items.isEmpty {
        let  alert = UIAlertController(title: "Completed", message: "Click below to reload datac", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "ok", style: .default, handler: { _ in
            // repopulate `items` array
            items = ["a", "b", "c"]
        }))
        present(alert, animated: true)
        return
    }

    let index = Int(arc4random_uniform(UInt32(items.count)))
    phrase = items[index]
    items.remove(at: index)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM