Is there a mapping in the standard library between Swift's String.Encoding and the IANA character set names?

Viewed 106

Does a mapping exist in the standard library between the String.Encoding enumeration and the standard IANA character set names, e.g., "UTF-8" for String.Encoding.utf8? I was not able to find one.

I'm aware that Foundation's CFStringEncoding can be mapped to IANA character set names, but I could not find a way to go from String.Encoding to CFStringEncoding. CFStringEncoding is just a type alias for UInt32, and the String.Encoding enumeration is backed by a UInt, but unless I've made some simple error, they do not seem to correspond.

1 Answers

The raw value of a String.Encoding is an NSStringEncoding and that can be converted to a CFStringEncoding with CFStringConvertNSStringEncodingToEncoding. The IANA charset name is then determined with CFStringConvertEncodingToIANACharSetName. This function returns an optional CFString which can be toll-free bridged to an optional Swift String.

Example:

let enc = String.Encoding.isoLatin2
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc.rawValue)
if let ianaName = CFStringConvertEncodingToIANACharSetName(cfEnc) as String? {
    print(ianaName) // iso-8859-2
}
Related