我想从给定数组中随机选择一个KanjiCard结构项,添加属性" kanji"到另一个临时数组并执行检查,如果yetShowedArray
中随机选择的struct.kanji重复随机选择,直到找到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)
答案 0 :(得分:0)
尝试在重复循环中再次刷新kanjiToTrack。如你所说,它是struct-value类型,所以你似乎在while子句中检查相同的kanjiToTrack。试试这个:
repeat {
random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
kanjiToShow = arrayToUse[random]
guard let kanjiToTrack = kanjiToShow.kanji else {return}
} while yetShowedArray.contains(kanjiToTrack)