8

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 } 
0

2 Answers 2

24

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 } 
Sign up to request clarification or add additional context in comments.

2 Comments

@Mike97 if the String instance (e.g. runningNumber) is only of a single Character or is empty (""), the resulting String instance after applying dropLast to the CharacterView of it will be an empty String (""). Applying dropLast() to an empty sequence will result in an empty (sub-)sequence. This is what I would expect. How would you define a different result?
You're right. But, in Xcode8.3 (in Sierra) just works fine while in Xcode8.2 (El Capitan) the same code was printing the last char (in case of only one char). So later I've cleaned the project, deleted the "Developper" folder.. re-run again and now print an empty line as expected. This was odd, sorry. PS I voted now for this answere ;-)
2

Remove last char from string/text in swift

var str1 = "123456789" str1.removeLast() print(str1) 

output:

12345678

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.