5

In earlier versions of Swift I could convert NSData to a UTF8 string thus:

let desc:String = String(data: requestData, encoding: NSUTF8StringEncoding)

(The documentation for NSString's init(data:NSData,encoding:NSStringEncoding) is here.)

In Swift 3 using Data I would expect something like

let desc:String = requestData.description(usedEncoding: String.Encoding.utf8)

But that does not exist (Data's documentation is here). What is the correct Swift 3 translation?

dumbledad
  • 12,928
  • 20
  • 97
  • 226

1 Answers1

15

It's actually the same syntax

init?(data: Data, encoding: String.Encoding)


let desc = String(data: requestData, encoding: .utf8)

Don't annotate types the compiler can infer.

vadian
  • 232,468
  • 27
  • 273
  • 287
  • Thanks for the answer. The annotations are not for the compiler they are for me, I'm not yet on top of Swift and I find it useful to have the type of my variables staring me in the face. It also highlights quickly when I am returned an unexpected type. – dumbledad Sep 22 '16 at 16:42
  • But you can make it worse especially when dealing with optionals. – vadian Sep 22 '16 at 16:44
  • For example when you annotate an optional which is a non-optional in practice. You can see that often in questions here on SO. In this case the compiler trusts you and does not complain. – vadian Sep 22 '16 at 16:46