0

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.

1
  • 2
    1 to the end of the array. Commented Jan 25, 2023 at 23:07

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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()

Comments

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.