Home > Software engineering >  Swift Array Open Range Operator
Swift Array Open Range Operator

Time:01-26

I've been learning Swift after coding on Android for a while. I was trying to figure out the use of the Open Range operator when used in an Array.

For e.g. Suppose we're working on an Array inside a function:

func operation(_ array:[Int]){

   for item in array[1...]{
      //1st element from the Array
       var currentItem = array[0]

     //Do something with the current item 
       
   }

}

In the above e.g., does the array[1...] mean; start from the element at index 1 and iterate till the end of the Array? Since the open range operator is supposed to run from 1 to infinity in this case.

CodePudding user response:

Here are the API doc's of the Array subscript operator you're calling: https://developer.apple.com/documentation/swift/array/subscript(_:)-4h7rl

The range expression is converted to a concrete subrange relative to this collection. For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array.

You could also write array[1...] as array.dropFirst()

CodePudding user response:

You can work with the following range operators

[1...10] means start at first index and end at 10th index including the 10th index. If there is no 10th index, the program will crash.

[5...10] means start at the fifth index and end at 10th index including the 10th index.

[0..<10] start at 0th index and end at 10th index but don't include the 10th index.

[...10] start from the initial point of the array. In this case 0th index and end at 10th index, including the 10th index.

[1...] start at the first index, and go all the way until there are no longer any more elements in the array. Program will not crash.

  • Related