API to encode/decode strings like in defaults output "\\U00e4r"

When I use the defaults command I see that special characters are encoded into ASCII by replaceing non-ASCII charagers with \\U and the numeric code for the unicode character in the output like "\\U00e4r"


Is there an API in Foundation or Cocoa that lets me encode and decode my own strings in way?


I need to have a string with a content like like "\\U00e4r" and decode it into another string to "är". Similarily I need to be able to convert a string with content "är" into another string with content "\\U00e4r". Naturally I can write functions to do this manually, by looping over every character in the string, but I guess such encoding/decoding functions must already exist in the apple APIs ready for use.


(I have not been able to find functions for such encoding/decoding when searcing the documentation and web. Probably because I have phrased the search incorreclty.)


I am programming in Swift on OS X 10.11.2. What is the easiest way to do these conversions of strings?


Thank you in advance for your help!

In case someone else pops into this:

I did not find any API to do this directly. I wrote my own function looping over the characters of the string to encode. I wrote another function searching for the substring "\\U" and then doing substring replacement to decode. In total less than 20 lines of Swift code.

You shouldn't be decoding or encoding strings stored in user defaults. If you use the NSUserDefaults methods 'stringForKey' and 'setStringForKey' it's going to be handled for you, transparently. You can't assume that what what 'defaults' *displays* represents the underlying storage form of the string (it's most likely stored as UTF-8 or UTF-16), or even if it is, that you should do anything about it manually.


Is there something else going on here that makes you think you have to handle encoding/decoding yourself?

I am not encoding/decoding strings for NSUSerDefaults. I am fully aware that I can feed the strings directly to NSUserDefaults.

I want to be able to produce an output that can be compared with the output of the defaults command for debugging/testing purposes.

Ah, well, no, there's no API to do this kind of generalized encoding/decoding. The nearest you could get, apart from custom coding as you've already done, might be NSRegularExpression. For tasks like recognizing the \\U… forms, you might also make use of NSScanner, though this case might not be difficult enough to go to that trouble.


I'd also point out that the form \\Uxxxx is ambiguous as to whether these might represent UTF-32 code units (abbreviated to 4 hex digits when possible) or UTF-16 code units. If the latter, you'll also have to deal with surrogate pairs.


Further, it's not obvious that some kind of UTF-8 representation won't show up for some strings.

API to encode/decode strings like in defaults output "\\U00e4r"
 
 
Q