Swikar Swikar - 1 year ago 129
Swift Question

How to implement functions count and dropLast in swift, IOS?

I am making calculator in Swift. Stuck in backspace button. If user press wrong digit then backspace button would help to delete digit off the display.

Though I wrote dropLast function and works. It return appropriate result. How to use count method, don't understand the return type of count method.

@IBOutlet weak var display: UILabel!
@IBAction func backspace() {
//how to use count method to check collection of elements
//dropLast drop the last digit and display result
let dropedDigit = dropLast(display.text!)
display.text = dropedDigit

Answer Source

How about something like this:

private func dropLast(text: String) -> String {
    let endIndex = advance(text.endIndex, -1)
    return text.substringToIndex(endIndex)

It calculates the index where you want to make the cut (endIndex of text - 1) and then returns the substring to this index. This function should drop the last character.

I am not using count method here, but for you reference Swift 1.2 introduces count(<#x: T#>) method that calculates length of sets including Strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download