重复一个数组的特定项

A. *_* M. 1 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"]
Run Code Online (Sandbox Code Playgroud)

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

Swe*_*per 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]     }
    }
}
Run Code Online (Sandbox Code Playgroud)

细节解释

用途flatMap:

yourArray.flatMap { $0 == "v" ? [$0, $0] : [$0] }
Run Code Online (Sandbox Code Playgroud)

基本上,这会检查数组的每个元素.如果是"v",请将其转换为["v", "v"].如果不是"v",请将其转换为包含该单个元素的数组.然后它会使所有这些阵列变平flatMap.

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

yourArray.flatMap { $0 == "v" ? [$0, $0, $0] : [$0] }
Run Code Online (Sandbox Code Playgroud)

或者重复一遍n:

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

使用playground来验证它:

//: 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)
Run Code Online (Sandbox Code Playgroud)