一旦删除项目后如何重新填充数组

时间:2019-06-27 00:34:24

标签: ios arrays swift uialertaction

我有一个数组,并删除了一些项,以便在从数组中调用元素时它们不会重复出现。但是,一旦调用了所有元素,我想在警报上单击“确定”后重新填充数组。我不知道该怎么做。有什么想法吗?

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)
    }
}

1 个答案:

答案 0 :(得分:1)

一般伪代码为:

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()

因此具有以下作用:

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)
}