我已经设法让我的代码随机选择对象并在我的视图控制器上显示图像,但有时随机选择的对象将是重复的,所以我需要能够删除存储在第二个数组中的所选对象第一个数组,所以他们第二次无法选择,但我不确定如何在我的代码中实现这一点,这是我的代码有效,但可能会选择重复:
@IBAction func drawCardsButtonPressed(_ sender: Any) {
cardsDrawnArray = []
if cardsDrawn == 1 {
let randomCards = cardsArray[Int(arc4random_uniform(UInt32(cardsArray.count)))]
cardsDrawnArray.append(randomCards.tarotImage)
tarotCardFive.image = cardsDrawnArray[0]
} else if cardsDrawn == 3 {
for _ in 0...2 {
let randomCards = cardsArray[Int(arc4random_uniform(UInt32(cardsArray.count)))]
cardsDrawnArray.append(randomCards.tarotImage)
}
tarotCardFour.image = cardsDrawnArray[0]
tarotCardFive.image = cardsDrawnArray[1]
tarotCardSix.image = cardsDrawnArray[2]
}
else if cardsDrawn == 5 {
for _ in 0...4 {
let randomCards = cardsArray[Int(arc4random_uniform(UInt32(cardsArray.count)))]
cardsDrawnArray.append(randomCards.tarotImage)
}
tarotCardTwo.image = cardsDrawnArray[0]
tarotCardFour.image = cardsDrawnArray[1]
tarotCardFive.image = cardsDrawnArray[2]
tarotCardSix.image = cardsDrawnArray[3]
tarotCardEight.image = cardsDrawnArray[4]
} else if cardsDrawn == 9 {
for _ in 0...8 {
let randomCards = cardsArray[Int(arc4random_uniform(UInt32(cardsArray.count)))]
cardsDrawnArray.append(randomCards.tarotImage)
}
tarotCardOne.image = cardsDrawnArray[0]
tarotCardTwo.image = cardsDrawnArray[1]
tarotCardThree.image = cardsDrawnArray[2]
tarotCardFour.image = cardsDrawnArray[3]
tarotCardFive.image = cardsDrawnArray[4]
tarotCardSix.image = cardsDrawnArray[5]
tarotCardSeven.image = cardsDrawnArray[6]
tarotCardEight.image = cardsDrawnArray[7]
tarotCardNine.image = cardsDrawnArray[8]
} else {
print(" Invalid Number")
}
}
非常感谢任何帮助解决此问题。
答案 0 :(得分:1)
而不是每次执行代码来获取随机卡,更好的方法是#34; shuffle"你的卡片组,然后只是以洗牌的顺序绘制它们。效率更高,你甚至不必考虑重复。
基本上,如果您的数组是数字1到10,它将从这样开始:
let cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
如果您运行循环,请选择"随机插槽"每次,你经常会得到重复(正如你所见)。所以......
let cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let shuffledCards = myShuffleFunc(cards)
你得到的结果如下:
[9, 2, 5, 6, 3, 1, 8, 10, 4, 7]
此时,你可以轻松地做到:
tarotCardOne.image = shuffledCards[0]
tarotCardTwo.image = shuffledCards[1]
tarotCardThree.image = shuffledCards[2]
tarotCardFour.image = shuffledCards[3]
tarotCardFive.image = shuffledCards[4]
或者你要分配它们。
看看这篇文章,了解一些好的改组代码:How do I shuffle an array in Swift?