8

How do I remove the last character of a string in Swift 4? I used to use substring in earlier versions of Swift, but the substring method is deprecated.

Here's the code I have.

temp = temp.substring(to: temp.index(before: temp.endIndex))
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Julia
  • 1,207
  • 4
  • 29
  • 47

3 Answers3

22

dropLast() is your safest bet, because it handles nils and empty strings without crashing (answer by OverD), but if you want to return the character you removed, use removeLast():

var str = "String"
let removedCharacter = str.removeLast() //str becomes "Strin"
                                        //and removedCharacter will be "g"

A different function, removeLast(_:) changes the count of the characters that should be removed:

var str = "String"
str.removeLast(3) //Str

The difference between the two is that removeLast() returns the character that was removed, while removeLast(_:) does not have a return value:

var str = "String"
print(str.removeLast()) //prints out "g"
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
13

You can use dropLast()

You can find more information on Apple documentation

OverD
  • 2,612
  • 2
  • 14
  • 29
2

A literal Swift 4 conversion of your code is

temp = String(temp[..<temp.index(before: temp.endIndex)])
  • foo.substring(from: index) becomes foo[index...]

  • foo.substring(to: index) becomes foo[..<index]

    and in particular cases a new String must be created from the Substring result.

but the solution in the4kmen's answer is much better.

Community
  • 1
  • 1
vadian
  • 274,689
  • 30
  • 353
  • 361