The issue is that you are invalidating the indices of your collection when inserting new elements. From the docs
Calling this method may invalidate any existing indices for use with this collection.
The most simple solution when you need to insert or remove multiple elements is to iterate your collection indices in reverse order:
var sampleArray = ["1","2","3","4","5","6","7","8","9","10"]
var insertions = ["header", "footer"]
for index in sampleArray.indices.dropFirst().reversed() where index.isMultiple(of: 3) {
sampleArray.insert(contentsOf: insertions, at: index)
}
sampleArray // ["1", "2", "3", "header", "footer", "4", "5", "6", "header", "footer", "7", "8", "9", "header", "footer", "10"]
If you would like to implement your own insert methods:
extension RangeReplaceableCollection {
mutating func insert<C>(contentsOf newElements: C, every nth: Int) where C : Collection, Self.Element == C.Element, Index == Int {
for index in indices.dropFirst().reversed() where index.isMultiple(of: nth) {
insert(contentsOf: newElements, at: index)
}
}
mutating func insert(_ newElement: Element, every nth: Int) where Index == Int {
for index in indices.dropFirst().reversed() where index.isMultiple(of: nth) {
insert(newElement, at: index)
}
}
}
Usage:
sampleArray.insert(contentsOf: insertions, every: 3)
// sampleArray.insert("header", every: 3)