使用For循环迭代数组30次

时间:2016-04-19 21:20:23

标签: arrays swift

我有一个包含8个元素的数组,我想逐个复制元素,直到新数组的数量达到30次。

我用于循环,而结果是只复制第一个元素30次。

    let myShift = ["D12","E","N12","N","Off","Rest1","Rest2","D"]
var myArray = [String]()
for i in myShift {
while myArray.count != 30 {
    myArray.append(i)   
}}

我读了一些关于地图的例子,我试图使用它,但它没有用。

4 个答案:

答案 0 :(得分:2)

由于它不太清楚你在寻找什么,这里有两个选择。

这个将重复数组的内容,直到它总共达到30个项目。它会保持秩序并循环它们。这会产生一个包含30个元素的数组。

let myShift = ["D12","E","N12","N","Off","Rest1","Rest2","D"]
var myArray = [String]()
(0..<30).forEach {
  myArray.append(myShift[$0 % myShift.count])
}

这个将产生一个数组,每个元素重复30次,总共240个元素。

let myShift = ["D12","E","N12","N","Off","Rest1","Rest2","D"]
let array = [[String]](count: 30, repeatedValue: myShift).flatMap { $0 }

答案 1 :(得分:0)

试试这个:

    let myShift = ["D12","E","N12","N","Off","Rest1","Rest2","D"]
    var myArray = [Array]()
    while myArray.count < 31 {
        myArray.append(myShift)   
    }}

答案 2 :(得分:0)

你可以这样做:

let myShift = ["D12","E","N12","N","Off","Rest1","Rest2","D"]
var myArray = [String]()

for i in myShift {
    myArray.appendContentsOf(Array(count: 30, repeatedValue: i))
}

答案 3 :(得分:0)

所以,我不是使用whilefor循环,而是喜欢使用一个好的旧双for循环。
以下代码生成一个包含240个项目的数组(8 * 30 = 240)。

let myShift = ["D12","E","N12","N","Off","Rest1","Rest2","D"]
var newArray = myShift

for i in 1...30 {
    for str in myShift {
        newArray.append(str)
    }
}

游乐场批准: playground

希望这会有所帮助:)