A. M.
A. M.

Reputation: 53

Repeat a specific item of an array

How to replace or repeat a specific item (v) of an array in Swift 3 / 4:

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

to get this:

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

or this:

["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"]

The reason is that element v inserts pauses (sec) between audio files (A, B, C, ...). The number of repetitions of the item v should be set via a SegmentedControl (1,2, ..., 6).

Upvotes: 1

Views: 136

Answers (3)

Sweeper
Sweeper

Reputation: 272895

Quick takeaway

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

Detail explains

Use flatMap:

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

Basically, this checks each element of the array. If it is "v", turn it into ["v", "v"]. If it is not "v", turn it into an array with that single element. Then it flattens all those arrays, hence flatMap.

You can also triple a specific item:

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

Or repeat it n times:

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

Use playground to verify it:

//: 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)

Upvotes: 9

Deepak Chaudhary
Deepak Chaudhary

Reputation: 1761

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
}

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

Upvotes: -1

Mohmmad S
Mohmmad S

Reputation: 5088

You can use insert(:at:) using the specific index of an element.

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

Output

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

You can wrap this in a function to repeat as much as you need.

Upvotes: 0

Related Questions