Swift Standard Library: transcode

Swift Standard Library: transcode

The transcode function lets to convert strings from one Unicode encoding to another, for example UTF16 to UTF8.

The definition you get when you command-click on the function is quite intimidating:

It is also incorrect; a type constraint with the same type expression on both sides of the == sign is not much of a constraint.

In plain English, what these constraints are saying is that we need an input
source (a GeneratorType) that generates elements that are compatible with
our input UnicodeCodecType and an output SinkType that can consume the output of our output encoder.

The following code takes the UTF32 codepoint for the “Grinning Face with Smiling Eyes”
emoji (I’m not kidding that is its official name!) and converts it to UTF8.

The values obtained seem to agree with the values I found on the ‘net, but we can verify using Cocoa to construct a string from the UTF8 values

In the playground for this tutorial the above code will print the emoji.

Download the Playground

The source for this and all other playgrounds in this series can be found on Github in the SwiftStandardLibraryPlaygrounds repository.


About idz

A professional software engineer dabbling in iOS app development.
This entry was posted in Swift, Swift Standard Library and tagged , , , , , , . Bookmark the permalink.

One Response to Swift Standard Library: transcode

  1. Pingback: EVERYTHING YOU WANT – Swift resources | swiftioscodetutorial

Leave a Reply