【问题标题】:How to add two elements repeatably after certain index to an Array如何在某个索引后重复添加两个元素到数组
【发布时间】:2021-02-04 09:11:56
【问题描述】:

有一个数组

var  sampleArray = ["1","2","3","4","5","6","7","8","9","10"]

有两个元素“header”和“footer

我想以这样的方式添加这两个元素,以便在原始数组的每个第三个索引之后附加这两个元素

预期输出

sampleArray = ["1","2","3", "header","footer" ,"4","5","6","header","footer""7","8","9""header","footer",10]

我通过提供的相同的内置方法进行谷歌搜索,我在下面找到

insert(_:at:)

但它不符合我的目的,它看起来是一个明显的问题,有没有人创造了这样的功能?

【问题讨论】:

  • 字符串数组
  • 我添加了报价,谢谢

标签: arrays swift xcode


【解决方案1】:

使用新数组正确组合

var result: [String] = []
for index in 0..< sampleArray.count {
   result.append(sample[index])
   if (index+1) % 3 == 0 {
       result.append("header")
       result.append("footer")

   }
}

【讨论】:

【解决方案2】:

您不能仅按该顺序插入索引 3、6、9 等,因为在索引 3 处插入后,要插入的下一个索引会发生变化(插入的元素数量会增加)。第三次插入时,它被移动了 两倍 您插入的元素数量,依此类推。如果考虑到这一点,那就很简单了:

var sampleArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
let sectionLength = 3
let separator = ["header", "footer"]
for (count, i) in stride(from: sectionLength, to: sampleArray.endIndex, by: sectionLength).enumerated() {
    sampleArray.insert(contentsOf: separator, at: i + count * separator.count)
}

创建新数组的替代解决方案:

let result = sampleArray.enumerated().flatMap { index, element in
    index % 3 == 2 ? [element] + separator : [element]
}

这里的想法是将flatMap 某些元素添加到该元素加上分隔符,并将其他元素添加到它们自己。 separator 应添加在 369 之后,它们分别位于索引 2、5 和 8 处。它们的索引都小于 3 的倍数,因此是 index % 3 == 2

【讨论】:

    【解决方案3】:

    问题是您在插入新元素时使集合的索引无效。来自文档

    调用此方法可能会使用于此集合的任何现有索引无效。

    当您需要插入或删除多个元素时,最简单的解决方案是以相反的顺序迭代您的集合索引:


    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 2014-09-21
      • 2014-11-13
      • 1970-01-01
      相关资源
      最近更新 更多