Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.


Swift Code Library: Printing a collection type with separators in between

Sometimes I need to create a string of values from a collection type with a certain separator in between them.

An integer array would look like this: 1, 2, 3, 4
Or this: 1 - 2 - 3 - 4

Writing an operation that does this should be as universally usable as possible. The best way is to add it to the CollectionType protocol.

This was the method I ended up using:

extension CollectionType {
    func descriptionWithSeparator(separator: String) -> String {
        return reduce("") { $0 == "" ? "\($1)" : $0 + separator + "\($1)" }

It was the shortest code I could come up with, but maybe not the fastest. I have not tested for speed.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment