Sneagan Sneagan - 2 years ago 218
Swift Question

Creating NSData from NSString in Swift

I'm trying to ultimately have an

with a valid
, but I can't seem to get my string data (coming from a
) into a usable

I've seen this method for going the other way:

NSString(data data: NSData!, encoding encoding: UInt)

But I can't seem to find any documentation for my use case. I'm open to putting the string into some other type if necessary, but none of the initialization options for
using Swift seem to be what I'm looking for.

Answer Source

In Swift 2 (or if you already have a NSString instance) it should be as simple as

let data = string.dataUsingEncoding(NSUTF8StringEncoding)

If you're using a version of swift < 2 and you instead have a swift String:

let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)

data is an Optional<NSData> (since the conversion might fail), so you'll need to unwrap it before using it, for instance:

if let d = data {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download