How can I remove the last character of a String in Swift 4?

Use removeLast():

var str = "String"
str.removeLast() //Strin

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" 

You can use dropLast()

You can find more information on Apple documentation


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.