Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete last character in Swift 3

Tags:

ios

swift3

I'm creating a simple calculator app and currently struggling at deleting the last character when a my button is tapped. I'm using the dropLast() method but I keep getting the error

Missing Argument for parameter #1 in call

@IBAction func onDelPressed (button: UIButton!)  {
     runningNumber = runningNumber.characters.dropLast()
     currentLbl.text = runningNumber
}
like image 635
Brewski Avatar asked Sep 21 '16 07:09

Brewski


People also ask

How do you remove the last character of a string in Swift?

Method 1- Using removeLast() Function Swift provide a in-built function named removeLast() to remove the last character from the given string. This method does not create a new string, it simply modify the original string.

How do I remove the first character from a string in Swift 5?

The dropFirst() method removes the first character of the string.

How do I find the length of a string in Swift?

To get the length of a string in Swift, call the String. count property.


1 Answers

Swift 4 (Addendum)

In Swift, you can apply dropLast() directectly on the String instance, no longer invoking .characters to access a CharacterView of the String:

var runningNumber = "12345"
runningNumber = String(runningNumber.dropLast())
print(runningNumber) // 1234

Swift 3 (Original answer)

I'll assume runningNumber is a String instance. In this case, runningNumber.characters.dropLast() is not of type String, but a CharacterView:

let foo = runningNumber.characters.dropLast()
print(type(of: foo)) // CharacterView

You need to use the CharacterView to instantiate a String instance prior to assigning it back to a property of type String, e.g.

var runningNumber = "12345"
runningNumber = String(runningNumber.characters.dropLast())
print(runningNumber) // 1234

I.e., for your case

@IBAction func onDelPressed (button: UIButton!)  {
  runningNumber = String(runningNumber.characters.dropLast())
  currentLbl.text = runningNumber
}
like image 126
dfrib Avatar answered Oct 28 '22 22:10

dfrib