我有一个包含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)
}}
我读了一些关于地图的例子,我试图使用它,但它没有用。
答案 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)