Swift supports two types of range operators to specify a range of values:
Closed range operator (a...b) specifies a range of values starting from a right up to b (inclusive).
Half-open range operator (a..<b) specifies a range of values starting from a right up to b, but not including b.
To demonstrate how these range operators work, consider the following example:
//prints 5 to 9 inclusive for num in 5...9 { print(num)// ww w . j a v a 2 s.c om }
The preceding code uses the closed range operator to output all the numbers from 5 to 9:
To output only 5 to 8, you can use the half-open range operator:
//prints 5 to 8 for num in 5..<9 { print(num)/*from w w w.j av a 2 s . c o m*/ }
The half-open range operator is useful when you are dealing with zero-based lists such as arrays.
The following code snippet is one good example:
//useful for 0-based lists such as arrays var fruits = ["apple","orange","pineapple","Json","Database"] for n in 0..<fruits.count { print(fruits[n])/* ww w. ja v a2 s.co m*/ }