如何在 swift 2 中重置 for 循环中的值
How to reset values in for loop in swift 2
我在使用以下代码行时遇到问题:
var participants = [String]()
var dict = [String: String]()
func createDictionary() {
var hat = participants
var loopCount = 0
for (keyIndex, key) in hat.enumerate() {
var valueIndex: Int {
var index: Int
repeat {
index = Int(arc4random_uniform(UInt32(hat.count)))
loopCount++
print(loopCount)
if loopCount > participants.count + 1000 {
createDictionary()
}
} while index == keyIndex || dict.values.contains(hat[index])
return index
}
dict[key] = hat[valueIndex]
}
}
我的目标是 "dict" 包含根据 "participants" 创建的字典。这个函数大部分时间会起作用,但有时会进入死循环。我试图做到这一点,如果它循环超过 1000 次左右,该函数将重复并重试。
我认为问题在于我无法重置 "keyIndex" 和 "key" 的值,因为它们是 "let constants"。但我不确定。
有没有办法重置循环以便获得这些值?或者重试整个函数?
因此,如果有人感兴趣,我可以弄清楚。我对此还是个新手,所以我相信其他人会更快地弄明白 :)
无论如何,我更新了代码如下:
var participants = [String]()
var dict = [String: String]()
func createDictionary() {
var hat = participants
var drawName = [String: String]()
var loopCount = 0
for (keyIndex, key) in hat.enumerate() {
var valueIndex: Int {
var index: Int
repeat {
loopCount++
index = Int(arc4random_uniform(UInt32(hat.count)))
} while index == keyIndex || drawName.values.contains(hat[index]) && loopCount < hat.count + 50
return index
}
drawName[key] = hat[valueIndex]
}
if loopCount > hat.count + 30 {
self.createDictionary()
} else {
dict = drawName
}
}
mathielo 是对的,我很可能以错误的方式看待这个问题。基本上我只是指示循环不要循环太多次,然后如果它必须尝试太多次才能获得一个值,则调用该函数。上面的代码在不冻结程序的情况下工作。
我在使用以下代码行时遇到问题:
var participants = [String]()
var dict = [String: String]()
func createDictionary() {
var hat = participants
var loopCount = 0
for (keyIndex, key) in hat.enumerate() {
var valueIndex: Int {
var index: Int
repeat {
index = Int(arc4random_uniform(UInt32(hat.count)))
loopCount++
print(loopCount)
if loopCount > participants.count + 1000 {
createDictionary()
}
} while index == keyIndex || dict.values.contains(hat[index])
return index
}
dict[key] = hat[valueIndex]
}
}
我的目标是 "dict" 包含根据 "participants" 创建的字典。这个函数大部分时间会起作用,但有时会进入死循环。我试图做到这一点,如果它循环超过 1000 次左右,该函数将重复并重试。
我认为问题在于我无法重置 "keyIndex" 和 "key" 的值,因为它们是 "let constants"。但我不确定。
有没有办法重置循环以便获得这些值?或者重试整个函数?
因此,如果有人感兴趣,我可以弄清楚。我对此还是个新手,所以我相信其他人会更快地弄明白 :)
无论如何,我更新了代码如下:
var participants = [String]()
var dict = [String: String]()
func createDictionary() {
var hat = participants
var drawName = [String: String]()
var loopCount = 0
for (keyIndex, key) in hat.enumerate() {
var valueIndex: Int {
var index: Int
repeat {
loopCount++
index = Int(arc4random_uniform(UInt32(hat.count)))
} while index == keyIndex || drawName.values.contains(hat[index]) && loopCount < hat.count + 50
return index
}
drawName[key] = hat[valueIndex]
}
if loopCount > hat.count + 30 {
self.createDictionary()
} else {
dict = drawName
}
}
mathielo 是对的,我很可能以错误的方式看待这个问题。基本上我只是指示循环不要循环太多次,然后如果它必须尝试太多次才能获得一个值,则调用该函数。上面的代码在不冻结程序的情况下工作。