Can't encode/decode string back an forth

Hi, folks, Maybe someone can help me with this, I'm not able to get the same string I had after UTF8 encoding it.


Here is the code:


let input = "Hello World"
let data = input.data(using: String.Encoding.utf8)!
var but = String(data, encoding: String.Encoding.utf8)



Here is the playground output


"Hello World"
<48656c6c 6f20576f 726c64>
"(<48656c6c 6f20576f 726c64>, Unicode (UTF-8))"



what it is tha I'm doing wrong? Thanks in advance!

Accepted Reply

As you see, you could have find the right syntax far easier, if Swift3/Xcode generated a proper diagnostic message.

(And some of the accepted proposals for Swift3 are suggesting that Swift should do so.)

So, I believe we can call it a bug, even if this is sort of "planned but not yet" thing.

Replies

An odd behaviour. You are getting the same result as this:

let tuple = (data, encoding: String.Encoding.utf8)
var tupleStr = String(tuple)


And the right syntax to decode binary Data to String is like this:

var but = String(data: data, encoding: String.Encoding.utf8)!


In my opinion, Swift should report error for `String(data, encoding: String.Encoding.utf8)`.

I'm not sure this is related to any of the poposals in swift.org. But this seems to a bug.

It's probably going to be covered by SE-0029, or one of the related proposals.

I'm already using swift 3 that's why there is no error, so I guess this is bug?

As you see, you could have find the right syntax far easier, if Swift3/Xcode generated a proper diagnostic message.

(And some of the accepted proposals for Swift3 are suggesting that Swift should do so.)

So, I believe we can call it a bug, even if this is sort of "planned but not yet" thing.