15

To remove a substring at a specified range, use the removeRange(_:) method:

1 let range = advance(welcome.endIndex, -6)..<welcome.endIndex
2 welcome.removeRange(range)
3 println(welcome)
4 // prints "hello"

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/ca/jEUH0.l

Hi there,

I don't fully understand the syntax and the function of line 1 in the code above.

Please explain using this string:

let welcome = "hello there"

This is what I've worked out:

"To change the start and end index, use advance()."
From: https://stackoverflow.com/a/24045156/4839671

A better documentation of advance() is welcomed. i.e. it's arguments

Use ..< to make a range that omits its upper value

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/ca/jEUH0.l

welcome.endIndex will be 11

Community
  • 1
  • 1
  • What is the difficulty? Strings have startIndex and endIndex. You must increase/decrease them via advance. A range is something like ``...`` or `index`..<``. – qwerty_so May 03 '15 at 19:09
  • I was not aware that variables(or constants) can hold ranges. –  May 03 '15 at 22:50

1 Answers1

23

Swift 2

We're going to use var since removeRange needs to operate on a mutable string.

var welcome = "hello there"

This line:

let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex

means that we start from the end of the string (welcome.endIndex) and move back by 6 characters (advance by a negative number = move back), then ask for the range (..<) between our position and the end of the string (welcome.endIndex).

It creates a range of 5..<11, which encompasses the " there" part of the string.

If you remove this range of characters from the string with:

welcome.removeRange(range)

then your string will be the remaining part:

print(welcome) // prints "hello"

You can take it the other way (from the start index of the string) for the same result:

welcome = "hello there"
let otherRange = welcome.startIndex.advancedBy(5)..<welcome.endIndex
welcome.removeRange(otherRange)
print(welcome) // prints "hello"

Here we start from the beginning of the string (welcome.startIndex), then we advance by 5 characters, then we make a range (..<) from here to the end of the string (welcome.endIndex).

Note: the advance function can work forward and backward.

Swift 3

The syntax has changed but the concepts are the same.

var welcome = "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
print(welcome) // prints "hello"

welcome = "hello there"
let otherRange = welcome.index(welcome.startIndex, offsetBy: 5)..<welcome.endIndex
welcome.removeSubrange(otherRange)
print(welcome) // prints "hello"
Eric Aya
  • 69,473
  • 35
  • 181
  • 253