1

I am trying to read the string from a Label and remove the last character form it.

This is how I am trying:

@IBAction func del(sender: UIButton) {
    let str = telephone.text!;
    let newstr = str.remove(at: str.index(before: str.endIndex))
    telephone.text = newstr;
}

When I run, I get an error:

"String" does not have a member named "remove"

Can someone help me figure out the problem? Just started learning swift :(

9
  • 1
    In Playground I can compile your code and it works just as expected. Try using let str = "Test" for testing purposes. Btw, you don't need to use ; at the end of a line. Commented Apr 6, 2017 at 6:55
  • I tried "Something" as text and the IDE still gives the same error :( Commented Apr 6, 2017 at 7:00
  • 1
    remove(at:) mutates the receiver and expects a variable. Commented Apr 6, 2017 at 7:01
  • what version of swift r u using? in swift 2.0 try this var name: String = "Dolphin" name.removeAtIndex(name.endIndex.predecessor()) Commented Apr 6, 2017 at 7:02
  • Try var str = telephone.text!. Commented Apr 6, 2017 at 7:02

3 Answers 3

1

remove(at:) mutates the receiver which must therefore be a variable string:

var str = telephone.text!
str.remove(at: str.index(before: str.endIndex))
telephone.text = str

Alternatively use substring(to:), which returns the new string instead of modifying the receiver:

let str = telephone.text!
let newstr = str.substring(to: str.index(before: str.endIndex))
telephone.text = newstr
Sign up to request clarification or add additional context in comments.

Comments

0

remove is defined as follows:

public mutating func remove(at i: String.Index) -> Character

See the mutating modifier? That means it mutates the instance on which the method is called. In your case, the instance is str, a constant. Since constants cannot be mutated, the code does not compile.

And since remove returns the removed character,

let newstr = str.remove(at: str.index(before: str.endIndex))

here newstr will not be storing the string with the last character removed.

You should rewrite the method like this:

telephone.text!.remove(at: telephone.text!.index(before: telephone.text!.endIndex))

Comments

0

You can use:

let idx = str.index(before: str.endIndex) // compute the index
let s = str.substring(to: idx)            // get the substring

2 Comments

Get the requested sub string.
But why an extra variable for the index?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.