Delete last character in Swift 3

后端 未结 2 1368
不知归路
不知归路 2021-01-05 03:49

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

相关标签:
2条回答
  • 2021-01-05 04:26

    Remove last char from string/text in swift

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

    output:

    12345678

    0 讨论(0)
  • 2021-01-05 04:32

    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
    }
    
    0 讨论(0)
提交回复
热议问题