0

I have the following code:

let kmInput: Int = (addKmInput.text!.replacingOccurrences(of: ".", with: "") as NSString).integerValue

Can I additionally replace occurrences of commas? Or is the only way to solve it this way:

let kmInput: Int = (addKmInput.text!.replacingOccurrences(of: ".", with: "").replacingOccurrences(of: ",", with: "")
Tom
  • 3,672
  • 6
  • 20
  • 52
  • 1
    You could use a regex expression to represent the things you want to replace, in your case I think "[.,]", you can look at this question to see how to replace with regex https://stackoverflow.com/questions/28503449/swift-replace-substring-regex – Quinn Aug 15 '19 at 14:43

1 Answers1

1

Yo can use replacingOccurrences that supports regular expressions, in this case [,.]

let result = string.replacingOccurrences(of: "[.,]", with: "", options: .regularExpression)

the full code would then be

let kmInput = Int(addKmInput.text!
    .replacingOccurrences(of: "[.,]", 
                          with: "", 
                          options: .regularExpression))
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • why not just a regular filter operation?`.filter { $0 != "," && $0 != "." }` or even better if OP just want to allow numbers in that field `filter { $0.isWholeNumber }` – Leo Dabus Aug 15 '19 at 19:54