-2

I am trying to make an expense calculator, where the user will simply type their expenses in this format "add Entertainment Movies 15" and the output will be printed as "Entertainment Movies $15.0". Since this user could enter any text I wanted to make this dynamic where as soon as a number is found like 15 in this case, the $ sign gets put in front of it.

Just wondering what is the right approach of doing it in Swift?

Shaun
  • 1
  • 1
    Not really an answer to your question directly, but you can ease your life w/ number formatter: https://stackoverflow.com/a/24960818/3397217 – LinusGeffarth Mar 04 '19 at 11:18
  • 1
    You might want to make the price a separate property. What if the user wants to enter `MacProok Pro 2018`? They didn't mean it cost $2018 (although it could have ). – LinusGeffarth Mar 04 '19 at 11:24

2 Answers2

1

Simple solution with regular expression. It replaces one or more digits (\\d+) followed by an optional dot and optional fractions digits (\\.\\d+)? with the $ sign plus the found partial string ($0).

let string = "add Entertainment Movies 15"
let result = string.replacingOccurrences(of: "\\d+(\\.\\d+)?", with: "$$0", options: .regularExpression)
vadian
  • 274,689
  • 30
  • 353
  • 361
1

you can do this:

func textDidChange(textField: UITextField){
    guard let text = textField.text else{return}

        if let numbersRange = text.rangeOfCharacter(from: .decimalDigits){
            text.insert("$", at: numbersRange.lowerBound)
        }

        print(text)

    }
Shahzaib Qureshi
  • 989
  • 8
  • 13
  • guard `let text = textField.text` will never fail. Just unwrap `text!` property. Its default value is an empty string. You can Also use optional chaining in this case `if let numbersRange = textField.text?.rangeOfCharacter(from: .decimalDigits) {`. This will probably insert the dollar symbol multiple times. – Leo Dabus Mar 04 '19 at 16:21