如何从数组中获取一个随机元素而不是多次抓取同一个元素?

时间:2014-12-14 20:56:40

标签: arrays uitableview swift random arc4random

当我使用arc4random_uniform()方法从数组中获取元素时,数组的相同元素通常会被多次抓取。我试图让它成为数组中的每个元素只被抓取一次。我尝试这样做的原因是UITableView中不止一个单元格具有相同的文本。这是UITableView

中单元格文本的数组
var definitions = ["Used to carry the pharoah","Used to carry bodies as a ceremony","Had a flat deck to carry a farmer's treasure","Daily, it made a trip around the world to carry Ra","Towed by smaller boats, carrying heavy objects","Used for business and pleasure by officials/nobles","Carried most Egyptians and some goods"]

在我的viewDidLoad()方法中,我这样做是为了调用definitions的随机元素:

self.boats = [Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))])]

如何更改我的代码,以便在UITableView中两个元素不会显示两次?谢谢!

1 个答案:

答案 0 :(得分:0)

保留随机索引值的列表,如果后续随机索引在该列表中,则跳过它并生成另一个随机索引。