How to Work with One-sided Ranges in Swift 4?

One-Sided ranges  introduces a new protocol RangeExpresstion and a set of prefix/postfix operators to form one-sided ranges, i.e. ranges where either the lower or upper bound is unspecified.




Infinite Sequence : You can use the one-sided range to construct an infinite sequence and it's replacement of enumerated() so don't start with 0.
let rangesInfinite = 1...       // Infinite values
rangesInfinite.contains(3) .    // true
rangesInfinite.contains(569999) // true
rangesInfinite.contains(0)      // false

Collection subscripts : The collocation's startIndex/endIndex with lower/upper bound change to gets elements.

Before the Swift 4.0 
let numbers = [1,2,3,4,5,6,7,8,9,10]
numbers[5..<numbers.endIndex] 
Now in Swift 4.0 
let numbers = [1,2,3,4,5,6,7,8,9,10]
numbers[5...]
Before the Swift 4.0 
let numbers = [1,2,3,4,5,6,7,8,9,10]
numbers[0..<5]
Now in Swift 4.0 
let numbers = [1,2,3,4,5,6,7,8,9,10]
numbers[..<5]

Pattern Matching : One-sided ranges also used in pattern matching constructs. its use in the case of switch statement. 
let value = 8
switch value {
case 10...:
    print("greater than ten")
case 10:
    print("ten")
case ..<10:
    print("less than ten")
default:
    fatalError("unreachable")
}

Thanks.
How to Work with One-sided Ranges in Swift 4? How to Work with One-sided Ranges in Swift 4? Reviewed by KIRIT MODI on 21:12:00 Rating: 5

No comments:

Powered by Blogger.