1

I have an array from 0 to 100.

let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"...."100"]

now, I want to add "-" after every 3 objects in an array.

So the output would be like this

array = ["0", "1", "2","-","3", "4", "5","-", "6", "7", "8", "-","9"...."100"]

So, How can I achieve this?

and what if i have model array instead of String array?

   struct SubCategory { 
        var title: String = ""
        var subTitle: String = "" 
  }

  let array = [SubCategory]() 
1
  • Does it have to be the case that you add it to a prexisting array? Or would it be acceptable to start with no array, and build the final array to match your specificatons? Commented Sep 8, 2018 at 8:58

2 Answers 2

7
let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

extension Array {
    func chunks(of size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            let n = Swift.min(size, count - $0)
            return Array(self[$0 ..< $0 + n])
        }
    }
}

let joined = Array(array.chunks(of: 3).joined(separator: ["-"]))
Sign up to request clarification or add additional context in comments.

3 Comments

If input is ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"] then output is ["0", "1", "2", "-", "3", "4", "5", "-", "6", "7", "8", "-", "9", "1", "0", "1", "1"] which is not right.
I've edited the answer. There was a bug in the last line. Copy-paste now ;)
Okay then UpVote from me.
4

Here is a way to directly create the result with a single map and a bit of math:

extension Array {
    func adding(_ element: Element, afterEvery n: Int) -> [Element] {
        guard n > 0 else { fatalError("afterEvery value must be greater than 0") }
        let newcount = self.count + self.count / n
        return (0 ..< newcount).map { (i: Int) -> Element in
            (i + 1) % (n + 1) == 0 ? element : self[i - i / (n + 1)]
        }
    }
}

Example:

let result = ["0", "1", "2", "3", "4", "5", "6"].adding("-", afterEvery: 3)
print(result)

Output:

["0", "1", "2", "-", "3", "4", "5", "-", "6"]

Example 2:

This time with [Int]:

let result2 = [1, 2, 3, 4, 5, 6].adding(0, afterEvery: 2)
print(result2)

Output:

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

Example 3:

With a custom struct:

struct SubCategory: CustomStringConvertible {
    var title = ""
    var subTitle = ""

    var description: String { return "SubCategory(title: \(title), subTitle: \(subTitle)" }
}

let array: [SubCategory] = [
    SubCategory(title: "2001", subTitle: "A Space Odyssey"),
    SubCategory(title: "Star Wars Episode 1", subTitle: "The Phantom Menace"),
    SubCategory(title: "Star Wars Episode 2", subTitle: "Attack of the Clones"),
    SubCategory(title: "Star Wars Episode 3", subTitle: "Revenge of the Sith"),
    SubCategory(title: "Star Wars Episode 4", subTitle: "A New Hope"),
    SubCategory(title: "Star Wars Episode 5", subTitle: "The Empire Strikes Back"),
    SubCategory(title: "Star Wars Episode 6", subTitle: "Return of the Jedi")
]

let result3 = array.adding(SubCategory(title: "none", subTitle: "none"), afterEvery: 3)
print(result3)

Output:

[SubCategory(title: 2001, subTitle: A Space Odyssey, SubCategory(title: Star Wars Episode 1, subTitle: The Phantom Menace, SubCategory(title: Star Wars Episode 2, subTitle: Attack of the Clones, SubCategory(title: none, subTitle: none, SubCategory(title: Star Wars Episode 3, subTitle: Revenge of the Sith, SubCategory(title: Star Wars Episode 4, subTitle: A New Hope, SubCategory(title: Star Wars Episode 5, subTitle: The Empire Strikes Back, SubCategory(title: none, subTitle: none, SubCategory(title: Star Wars Episode 6, subTitle: Return of the Jedi]


Mutating version

Here is a version that mutates the original array instead of creating a new one:

extension Array {
    mutating func add(_ element: Element, afterEvery n: Int) {
        guard n > 0 else { fatalError("afterEvery value must be greater than 0") }
        var index = (self.count / n) * n
        while index > 0 {
            self.insert(element, at: index)
            index -= n
        }
    }
}

Example:

var array = ["0", "1", "2", "3", "4", "5", "6"]
array.add("-", afterEvery: 3)
print(array)

Output:

["0", "1", "2", "-", "3", "4", "5", "-", "6"]

4 Comments

Edited question for different case.
It will work with an array of any type. The element you are adding must be the same type as the elements already in the array.
Great..!! Thanks @vacawama
I added a mutating version as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.