Swift - 3.0 : Range Operators



Range Operators: 


In order to avoid traditional way of iterating through the range of values, Swift has introduced, shorthand, handy, Range Operators. Swift has two type of range operators by which you can iterate through the range of values. These are shorthand for to avoid traditional way of iterating through values using for loop etc.

Traditional Iteration: 

for (var i = 0; i<=5;i += 1) {
    // for iterating through values

}

Range Operator Type:
  1. Closed Range Operator  (a ... b) - range includes a and b.
  2. Half - Open Range Operator (a ..< b ) range includes an only.
1. Closed Range Operator - This operator defines as (x ... z) values from x to z. In this range of values 'x' and 'z' both are included in the range. But you should remember that value 'x' must not be
greater than 'z' value. The compiler will give an error. If 'x' and 'z' are same then it will run successfully.

Example: Just adding very simple e. g.

(a)

for i in 0 ... 5 {
    print("index \(i)")
}

Print: 

index 0
index 1
index 2
index 3
index 4
index 5

(b)

for i in 0 ... 0 {
    print("index \(i)")
}

Print: 

index 0

As you can see both it includes '0' and '5'.

2. Half - Open Range Operator - This operator defines as (x ... z) values from x to z. In this range of values 'x' will include only. It called as Half Open because it will include only x, but not it's final value. 

Note: If 'x' and 'z' will be equal then resulting range will have no values (empty).  

Example: Just adding very simple e. g.

(a)

for i in 0 ..< 5 {
    print("index \(i)")
}

Print: 

index 0
index 1
index 2
index 3
index 4

(b)

for i in 0 ..< 0 {
    print("index \(i)")
}

Print: 

As you can see (a) it includes '0' only.

Updated: As Swift 4 came and Range Operators: "One-Sided Ranges" operators.
In this operator, its starts from one side and continue as far as possible in one direction.

let names = ["iOS", "WatchOS", "TVOS", "Swift"]
for name in names[2...] {
    print(name)
}
// TVOS
// Swift


for name in names[...2] {
    print(name)
}
// iOS
// WatchOS

// TVOS

half-open range operator

for name in names[..<2] {
    print(name)
}
// iOS
// WatchOS


you can also check whether one side range operator you can also check particular value.

let range = ...5
range.contains(7)   // false
range.contains(4)   // true
range.contains(-1)  // true



If you like what you've read today then you can check other blogsStay tuned for next topic

Comments

  1. Nice artice. Please check android tutorial http://www.sunilandroid.com

    ReplyDelete

Post a Comment

Popular posts from this blog

Copy Vs Mutable Copy in iOS

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Closures in Swift - Part 1