vichhai vichhai - 1 year ago 137
Swift Question

How To Create Range in Swift?

In Objective-c we create range by using NSRange

NSRange range;

So how to create range in Swift?

Answer Source

Swift ranges are more complex than NSRange. The Swift Range type is "a collection of consecutive discrete index values." If you want to try and figure out what that means, read this and this. I'll just show you how to create them.

Closed Range: a...b

This range operator creates a Swift Range which includes both element a and element b.


let myRange = 1...3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c", "d"]

Half-Open Range: a..<b

This range operator includes element a but not element b.


let myRange = 1..<3

let myArray = ["a", "b", "c", "d", "e"]
myArray[myRange] // ["b", "c"]


You can (must) still use NSRange at times in Swift (when making attributed strings, for example), so it is helpful to know how to make one.

let myNSRange = NSRange(location: 3, length: 2)

Note that this is location and length, not start index and end index. The example here is similar in meaning to the Swift range 3..<5. However, since the types are different, they are not interchangeable.

Ranges with Strings

The ... and ..< range operators are a shorthand way of creating ranges. The long way to create the same range in the second example above would have been

let myRange = Range<Int>(start: 1, end: 3) // 1..<3

You can see that the index type here is Int. That doesn't work for String, though, because Strings are made of Characters and not all characters are the same size. (Read this for more info.) An emoji like