Slicing Arrays in Swift

Here’s an Array extension which adds a flexible array slice() method to Arrays. First, a few examples:

Return a new Array starting at element 3 through element 4, both inclusive:

[1,2,3,4,5].slice(2, 3)
//[3, 4]

Return a new Array starting at element 4 and through the end:

[1,2,3,4,5].slice(3)
//[4, 5]

Return a new Array starting at element 3 and through the end:

[1,2,3,4,5].slice(2,-1)
//[3, 4, 5]

Return a new Array in reverse order:

[1,2,3,4,5].slice(-1,0)
//[5, 4, 3, 2, 1]

Return a new Array in reverse order, starting at the second to last element and through the second element:

[1,2,3,4,5].slice(-2,1)
//[4, 3, 2]

Array Slice Extension

extension Array {
  func slice(args: Int...) -> Array {
    var s = args[0]
    var e = self.count - 1
    if args.count > 1 { e = args[1] }
    
    if e < 0 {
      e += self.count
    }
    
    if s < 0 {
      s += self.count
    }
    
    let count = (s < e ? e-s : s-e)+1
    let inc = s < e ? 1 : -1
    var ret = Array()
    
    var idx = s
    for var i=0;i<count;i++  {
      ret.append(self[idx])
      idx += inc
    }
    return ret
  }
}

One thought on “Slicing Arrays in Swift

  1. Very nice! Note that you can slice arrays by using ranges, e.g. “A[1…3]”. You can even replace ranges as well.

    Like

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