Suragch Suragch - 1 year ago 299
Swift Question

How does String substring work in Swift 3

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)

where the second line was giving me the following error

Value of type 'String' has no member 'substringWithRange'

I see that
does have the following methods now:

str.substring(to: String.Index)
str.substring(from: String.Index)
str.substring(with: Range<String.Index>)

These were really confusing me at first so I started playing around index and range. This is a followup question and answer for substring. I am adding an answer below to show how they are used.

Answer Source

All of the following examples use

var str = "Hello, playground"

substring(to: String.Index)

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.

substring(from: String.Index)

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

substring(with: Range)

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download