In Objective-c we create range by using NSRange
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.
This range operator creates a Swift
Range which includes both element
a and element
let myRange = 1...3 let myArray = ["a", "b", "c", "d", "e"] myArray[myRange] // ["b", "c", "d"]
This range operator includes element
a but not element
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.
..< 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