I've been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing with substrings things got confusing.
Specifically I was trying the following:
let str = "Hello, playground"
let prefixRange = str.startIndex..<str.startIndex.advancedBy(5)
let prefix = str.substringWithRange(prefixRange)
Value of type 'String' has no member 'substringWithRange'
All of the following examples use
var str = "Hello, playground"
This takes the substring from the beginning of the string to the specified index.
let index = str.index(str.startIndex, offsetBy: 5) str.substring(to: index) // Hello
If you don't understand
String.Index, see my previous answer.
This takes the substring from the specified index to the end of the string.
let index = str.index(str.startIndex, offsetBy: 7) str.substring(from: index) // playground
This one just gives you a substring based on the Range you pass in. Once you have the range, it's easy. Although still not as convenient as the old
NSRange, this is a definite improvement over Swift 2 ranges.
let start = str.index(str.startIndex, offsetBy: 7) let end = str.index(str.endIndex, offsetBy: -6) let range = start..<end str.substring(with: range) // play