重复数组的特定项目

时间:2018-11-15 06:44:47

标签: swift

如何在Swift 3/4中替换或重复数组的特定项目(v):

["A","s","B","v","C","s","D","v","E","s"]

得到这个:

["A","s","B","v","v","C","s","D","v","v","E","s"]

或者这个:

["A","s","B","v","v","v","C","s","D","v","v","v","E","s"]
["A","s","B","v","v","v","v","C","s","D","v","v","v","v","E","s"]

原因是元素v在音频文件(A,B,C,...)之间插入了暂停(秒)。项目v的重复次数应通过SegmentedControl(1,2,...,6)设置。

3 个答案:

答案 0 :(得分:9)

快速外卖

extension Array where Element == String  {
    func repeatItem(_ item: Element, times n: Int) -> Array<Element> {
        return flatMap { $0 == item ? Array(repeating: $0, count: n) : [$0]     }
    }
}

详细说明

使用flatMap

yourArray.flatMap { $0 == "v" ? [$0, $0] : [$0] }

基本上,这会检查数组的每个元素。如果是"v",请将其变成["v", "v"]。如果不是"v",则将其转换为具有单个元素的数组。然后它将所有这些数组展平,因此flatMap

您还可以将特定项目增加三倍:

yourArray.flatMap { $0 == "v" ? [$0, $0, $0] : [$0] }

或重复n次:

yourArray.flatMap { $0 == "v" ? Array(repeating: $0, count: n) : [$0] }

使用游乐场进行验证:

//: Playground - noun: a place where people can play
import Foundation

var inputArray = ["A","s","B","v","C","s","D","v","E","s"]
var expectArray2 = ["A","s","B","v","v","C","s","D","v","v","E","s"]
var expectArray3 = ["A","s","B","v","v","v","C","s","D","v","v","v","E","s"]
var expectArray4 = ["A","s","B","v","v","v","v","C","s","D","v","v","v","v","E","s"]

extension Array where Element == String  {
    func repeatItem(_ item: Element, times n: Int) -> Array<Element> {
        return flatMap { $0 == item ? Array(repeating: $0, count: n) : [$0] }
    }
}

print(inputArray.repeatItem("v", times: 2) == expectArray2)
print(inputArray.repeatItem("v", times: 3) == expectArray3)
print(inputArray.repeatItem("v", times: 4) == expectArray4)

答案 1 :(得分:0)

您可以使用insert(:at:)并使用元素的特定索引。

var foo = [0,1,2,3,4,5,6,7]
foo.insert(0, at: foo[0])

输出

  

[0,0,1,2,3,4,5,6,7]

您可以将其包装在函数中,以根据需要重复多次。

答案 2 :(得分:-1)

let array : [String] = ["A","s","B","v","C","s","D","v","E","s"]
print(replaceItem(array: array, item: "v"))

//Method

func replaceItem(array : [String], item : String) -> [String] {
    var newAr: [String] = []
    for arItem in array{
        newAr.append(arItem)
        if arItem == item {
            newAr.append(arItem)
        }
    }
    return newAr
}

输出: [“ A”,“ s”,“ B”,“ v”,“ v”,“ C”,“ s”,“ D”,“ v”,“ v”,“ E”,“ s”] < / p>