0

I've got a textfield input that returns a string like this:

let name = "B\U00f6se"

how can I convert the umlaut so \U00f6 (and any other special character) gets replaced with it's proper equivalent:

name = "Böse";

Thanks for your help!

//Seb

Seb
  • 983
  • 1
  • 11
  • 26
  • So the user types the characters "B", "\", "U", "0", ... into the text field? Then this might help: http://stackoverflow.com/questions/17759574/best-way-to-convert-back-and-forth-from-unichars-to-display-characters-objectiv (and translating that form Objective-C to Swift should not be too difficult :) – Martin R Jan 18 '15 at 22:41
  • 1
    _Why_ does your input return that? It is possible to type ö directly in iOS. – matt Jan 18 '15 at 22:41
  • @matt maybe that's the question. I'm using a form based on this library: [SwiftForms](https://github.com/ortuman/SwiftForms). And it returns all the input in a dictionary. Whenever there is a special character it returns something like the above. Any ideas? – Seb Jan 18 '15 at 22:49
  • @Seb: The `description` method of `NSDictionary` and `NSArray` use the `\Unnnn` syntax to print any non-ASCII character. But as soon as you assign a dictionary value to a string, you should see what you expect. – See http://stackoverflow.com/a/17340103/1187415 for an example – Martin R Jan 18 '15 at 22:51
  • @MartinR I see. OK so the Dictionary prints to the logs like this: `{ gender = M; name = "\U00d6ser" }` How do I assign name to a string correctly? – Seb Jan 18 '15 at 23:05
  • If the user enters an ö you've _got_ the ö. There is no there there. – matt Jan 18 '15 at 23:09

2 Answers2

0

The description method of NSArray and NSDictionary use \Unnnn escape sequences for all non-ASCII characters.

In the Xcode sample project that comes with SwiftForms, the submit method displays this description to the user:

func submit(_: UIBarButtonItem!) {

    let message = self.form.formValues().description
    let alert: UIAlertView = UIAlertView(title: "Form output", message: message, delegate: nil, cancelButtonTitle: "OK")
    alert.show()
}

and the effect is that you see for example

lastName = "B\U00f6se";

But the description method is only suited for debugging or logging. What you should do instead is to enumerate all keys and values:

for (key, value) in self.form.formValues() {
    println("\(key) = \(value)")
}

which would show you

lastName = Böse

or retrieve the form values that you are interested in:

if let lastName = self.form.formValues()["lastName"] as? String {
    println(lastName) // Böse
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks to your comments I just figured out something very similar! Thanks for your help! – Seb Jan 18 '15 at 23:17
0

There is a simpler way.

let name = "B\u{00f6}se"
pinrtln(name)

For more detail look at this entry

Kalenda
  • 1,847
  • 14
  • 15