我想从给定数组中随机选择一个 KanjiCard 结构项,将属性“kanji”添加到另一个临时数组中并执行检查,如果随机选择的 struct.kanji 存在于
yetShowedArray
中,则重复随机选择,直到您找到一个 yetShowedArray
中不存在汉字的结构体以便使用它
实际的重复/同时流程并不能确保它发生。
//test for the not repeating run *************************************************************************************
//check if the two array have the same number of items
guard arrayToUse.count != yetShowedArray.count else {
print("finished all the kanji")
var matching = 0
for element in arrayToUse {
if yetShowedArray.contains(element.kanji!){
matching += 1
}
}
print("matching kanji are : \(matching)")
return
}
var random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
//Instance
kanjiToShow = arrayToUse[random]
guard let kanjiToTrack = kanjiToShow.kanji else {
print("kanjiToTrack is nil!!!")
return
}
if yetShowedArray.contains(kanjiToTrack){
print("contained")
repeat {
random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
kanjiToShow = arrayToUse[random]
} while yetShowedArray.contains(kanjiToTrack)
print("refreshed random")
}
else {
print("never used before")
}
yetShowedArray.append(kanjiToTrack)
print(yetShowedArray)
print("arrayToUse: \(arrayToUse.count) yetShowedArray: \(yetShowedArray.count)")
//test for the not repeating run *************************************************************************************
解决方案
在 Anton Novoselov 的回答后发现
我将 let
kanjiToTrack
更改为 var,然后在重复循环内刷新它
//Instance
kanjiToShow = arrayToUse[random]
guard var kanjiToTrack = kanjiToShow.kanji else {
print("kanjiToTrack is nil!!!")
return
}
if yetShowedArray.contains(kanjiToTrack){
print("contained")
repeat {
random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
kanjiToShow = arrayToUse[random]
kanjiToTrack = kanjiToShow.kanji!
} while yetShowedArray.contains(kanjiToTrack)
print("refreshed random")
}
else {
print("never used before")
}
第二种解决方案
let random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
//Instance
kanjiToShow = arrayToUse[random]
guard kanjiToShow.kanji != nil else {
print("kanjiToTrack is nil!!!")
return
}
arrayToUse.remove(at: random)
尝试在重复循环内再次刷新 kanjiToTrack。正如您所说,它是结构-值类型,因此您似乎在 while 子句中检查相同的 kanjiToTrack 。试试这个:
repeat {
random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
kanjiToShow = arrayToUse[random]
guard let kanjiToTrack = kanjiToShow.kanji else {return}
} while yetShowedArray.contains(kanjiToTrack)