Swift: fixing “unable to decode playground data”

The dreaded “unable to decode playground data” error just happened to me and I thought I’d share my solution. What happened was this. I pasted some code from a Word document into the playground and immediately bad things started happening. The Playground kept complaining. So I cut out the pasted material and everything went back to behaving.

I set out to figure out what was going wrong. I tried stripping the text, first assuming the issues might involve rich text or something like that. But no, the error persisted. So then I tried typing the code in directly, skipping the paste. This time, the playground worked. Something was traveling with the paste, even stripped down to text, that was killing the playground.

So I pasted my copied code into one text file and the manually-typed version into another and diff’ed them at the command line. Immediate a problem jumped out, encouraging me to list the two files there. In one case, I was using standard returns, in the other (the one copied from Word) ^M’s. You can see this in the following shot: (Click it to expand to full size)

Screen Shot 2015-03-23 at 10.26.00 AM

To test, I created a new playground, pasted in the problematic code and once again got an error. Then at the end of each line, I performed a delete and then a manual return. Problem fixed. Everything ran properly.

What’s interesting about all this is that the issue wasn’t apparent until the command line. Everything looked identical when inspected in TextEdit and when I peeked at the contents.swift file. Here’s the hex dump of the non-working contents.swift (top) and working (bottom). If you open the full-size version, you’ll see that the error appears when the lines end with ^M (0x0d) versus ^J (0x0a).

Screen Shot 2015-03-23 at 10.36.29 AM

I accidentally slipped one extra 0x0a line return in the non-working version, so there’s an extra 0a there at the start of the second-to-last line.

Presumably, the decoding error is not limited to ^M vs ^J, but hopefully this write-up will show up in someone’s future web search and maybe help them out of a sticky situation.




  • Hi Erica,

    Nice work, I was pasting from a pdf book and had the same problems. This is actually a very annoying problem if you want to use playground.

    Due to differences in new line symbols Unix (n) and Windows (rn) which you can see on your hex dump (or od -a command) one needs to remove the r character from contents.swift. I found two easy ways to do it using (on OS X) commands:

    1. tr -d “r” outputfile
    2. cat inputfile | col -b > output file

  • This showed up in my web search (here in the future) and helped me out of a sticky situation. Thanks!

    • Waving back from the future!