2

I'm using Swift5's UserDefaults to store text key pair preferences. What some users of my app have been doing is accidentally adding a space before or after the string which is then causing problems.

Please can someone advise me on how I can intercept the submitted text string entered in settings and remove whitespaces before it is saved?

pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • 2
    Can you edit your question and add a [example] to illustrate the issue? – koen Sep 11 '20 at 18:33
  • 1
    If they're accidentally surrounding the string in whitespace, you could trim it. `let trimmedString = string.trimmingCharacters(in: .whitespaces)` – JarWarren Sep 11 '20 at 18:38
  • I hope my answer has solved your question. Please consider to accept my answer if it helped you and other SO users may benefit from that. – Eric Hua Sep 17 '20 at 20:26

2 Answers2

2

Before your user-entered String gets saved, do this to trim all leading and trailing whitespaces:

let rawStr = " YOUR USER ENTERED STRING  "
let trimmedStr = rawStr.trimmingCharacters(in: .whitespaces)

// Save `trimmedStr` into UserDefaults here

If you also want to trim newlines, use .whitespacesAndNewlines instead of .whitespaces.

Eric Hua
  • 976
  • 2
  • 11
  • 29
-1
var text = "Dummy Text   "

print(text.trimmingCharacters(in: .whitespaces))

//Output --> DummyText

For newline whitespacesAndNewlines

Jaykant
  • 349
  • 4
  • 11