Lukas Lukas - 7 months ago 9
Swift Question

Writing a String to an NSOutputStream in Swift

I'm trying to write a

String
to an
NSOutputStream
in Swift. Writing Strings that way with Objective C usually works by passing it as NSData

NSData *data = [[NSData alloc] initWithData:[mystring dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];


This does not work with swift

var data: NSData = mystring.dataUsingEncoding(NSUTF8StringEncoding)!
outputStream.write(data, maxLength: data.length)


this yields the error


'NSData' is not convertible to 'UnsafePointer'


for the line that writes the data to the stream.

How would you write a String to an NSOutputStream in Swift?

Answer

There are two issues here. The first is that you're passing data to outputStream.write() and not data.bytes (like you passed [data bytes] in your Objective-C code). The second issue is that data.bytes returns an UnsafePointer<Void>, but NSOutputStream.write() takes an UnsafePointer<UInt8>. Luckily, UnsafePointer has a way to convert between types:

/// Convert from a UnsafePointer of a different type.
///
/// This is a fundamentally unsafe conversion.
init<U>(_ from: UnsafePointer<U>)

Putting those things together makes your code look something like this:

let data: NSData = mystring.dataUsingEncoding(NSUTF8StringEncoding)!
outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
Comments