Flatten an Array to a String (Swift Extension)

Here’s a array extension which concatenates the ‘string’ representation of each items in the array, with the given String as a separator between each item.

extension Array {
  func combine(separator: String) -> String{
    var str : String = ""
    for (idx, item) in enumerate(self) {
      str += "\(item)"
      if idx < self.count-1 {
        str += separator
      }
    }
    return str
  }
}

Since its an extension object, we can use it on any array:

println([1,2,3,4,5].combine(", "))

gives us:

1, 2, 3, 4, 5

2 thoughts on “Flatten an Array to a String (Swift Extension)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s