我该如何正确进行循环

时间:2019-07-19 01:16:03

标签: ios swift algorithm swift4 programming-languages

我想在数组的第3位添加“ 5”

var myList: [String] = ["U.S", "Spain", "China", "Brazil", "India" , "Canada", "Germany", "UK", "Dubai", "Russia", "Japan", "Italy", "France", "Australia", "Thailand", "Mexico"]

var i = 0
for name in 0...myList.count {
    i = i + 1
    if  i % 3 == 0 {
        myList.insert("\(5)", at: i )
    }
}
print("\(myList)")

OutPut是:

["U.S", "Spain", "China", "5", "Brazil", "India", "5", "Canada", "Germany", "5", "UK", "Dubai", "5", "Russia", "Japan", "5", "Italy", "France", "Australia", "Thailand", "Mexico"]

但是在array中的16个位置之后,我无法将所有5个放入我的数组中,因为myList的数组总共有16个计数....所以我怎样才能正确地将5个放入我的数组中

1 个答案:

答案 0 :(得分:4)

这里的问题是,您正在对数组进行突变(在迭代时更改其元素),因此,实际要做的就是以相反的顺序插入元素。尝试这样:

var myList = ["U.S", "Spain", "China", "Brazil", "India", "Canada", "Germany", "UK", "Dubai", "Russia", "Japan", "Italy", "France", "Australia", "Thailand", "Mexico" ]

for index in myList.indices.dropFirst().reversed() where index % 3 == 0 {
    myList.insert("5", at: index)
}

print(myList)   // "["U.S", "Spain", "China", "5", "Brazil", "India", "Canada", "5", "Germany", "UK", "Dubai", "5", "Russia", "Japan", "Italy", "5", "France", "Australia", "Thailand", "5", "Mexico"]\n"