小编典典

在Swift中将字符串写入NSOutputStream

swift

我试图写一个StringNSOutputStream斯威夫特。使用Objective C以这种方式编写字符串通常可以将其作为NSData传递

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

这行不通

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

这产生了错误

“ NSData”不可转换为“ UnsafePointer”

用于将数据写入流的行。

您将如何在Swift中将字符串写入NSOutputStream?


阅读 329

收藏
2020-07-07

共1个答案

小编典典

这里有两个问题。首先是您要传递data给(outputStream.write()而不是)data.bytes(就像您[data bytes]在Objective-
C代码中传递的那样)。第二个问题是data.bytes返回UnsafePointer<Void>,但NSOutputStream.write()UnsafePointer<UInt8>。幸运的是,UnsafePointer有一种方法可以在类型之间进行转换:

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

将这些内容放在一起会使您的代码看起来像这样:

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