问题是您在插入新元素时使集合的索引无效。来自文档
调用此方法可能会使用于此集合的任何现有索引无效。
当您需要插入或删除多个元素时,最简单的解决方案是以相反的顺序迭代您的集合索引:
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"]
如果您想实现自己的插入方法:
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)
}
}
}
用法:
sampleArray.insert(contentsOf: insertions, every: 3)
// sampleArray.insert("header", every: 3)