How To Create Range in Swift?

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 aand element b.

Half-Open Range: a..<b

NSRange

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