你好我是新手,我需要一些帮助。有没有办法可以将循环计数的值作为索引:
var groups = [[String]]()
groupA.append(arr[randoms[0]])
groupA.append(arr[randoms[1]])
groupB.append(arr[randoms[2]])
groupB.append(arr[randoms[3]])
groupC.append(arr[randoms[4]])
groupC.append(arr[randoms[5]])
groupD.append(arr[randoms[6]])
groupD.append(arr[randoms[7]])
groupE.append(arr[randoms[8]])
groupE.append(arr[randoms[9]])
groups.append(groupA)
groups.append(groupB)
groups.append(groupC)
groups.append(groupD)
groups.append(groupE)
我希望随机数组的索引0-10来自一个循环或者在某种程度上是动态的,有没有办法用swift实现这个?
答案 0 :(得分:1)
我认为您正在寻找enumerated()
功能......
import Foundation
let randoms = [arc4random(),arc4random(),arc4random(),arc4random(),]
randoms.enumerated().forEach {
print($0,$1)
}
在Xcode Playground中试试。
答案 1 :(得分:0)
你可能正在寻找这种东西。让我们摆脱random
而只是 shuffle arr
来生成随机顺序的实际值列表。 (Stack Overflow上有很多数组重排代码,所以我不打算告诉你如何做到这一点。)然后我们也可以摆脱你的中间数组,直接处理数组的内部数组 - 数组groups
:
var groups : [[String]] = Array(repeating: [], count: 5)
var shuffled = ["hey", "ho", "nonny", "no", "sis", "boom", "bah", "yo", "hi", "lo"]
var next = 0
for ix in stride(from:0, to:9, by:2) {
for ixx in 0..<2 {
groups[next].append(shuffled[ix+ixx])
}
next += 1
}
groups // [["hey", "ho"], ["nonny", "no"], ["sis", "boom"], ["bah", "yo"], ["hi", "lo"]]
我们实际上可以使用map
(如Swift: what is the right way to split up a [String] resulting in a [[String]] with a given subarray size?所述)更简明扼要地表达:
let shuffled = ["hey", "ho", "nonny", "no", "sis", "boom", "bah", "yo", "hi", "lo"]
let chunkSize = 2
let groups = stride(from: 0, to: shuffled.count, by: chunkSize).map {
Array(shuffled[$0..<min($0 + chunkSize, shuffled.count)])
}
groups // [["hey", "ho"], ["nonny", "no"], ["sis", "boom"], ["bah", "yo"], ["hi", "lo"]]
更好的是,我们可以将它作为Array的扩展:
extension Array {
func chunked(by chunkSize:Int) -> [[Element]] {
let groups = stride(from: 0, to: self.count, by: chunkSize).map {
Array(self[$0..<[$0 + chunkSize, self.count].min()!])
}
return groups
}
}
let shuffled = ["hey", "ho", "nonny", "no", "sis", "boom", "bah", "yo", "hi", "lo"]
let groups = shuffled.chunked(by:2)
groups // [["hey", "ho"], ["nonny", "no"], ["sis", "boom"], ["bah", "yo"], ["hi", "lo"]]