我试图写一个String给NSOutputStream斯威夫特。使用Objective C以这种方式编写字符串通常可以将其作为NSData传递
String
NSOutputStream
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?
这里有两个问题。首先是您要传递data给(outputStream.write()而不是)data.bytes(就像您[data bytes]在Objective- C代码中传递的那样)。第二个问题是data.bytes返回UnsafePointer<Void>,但NSOutputStream.write()取UnsafePointer<UInt8>。幸运的是,UnsafePointer有一种方法可以在类型之间进行转换:
data
outputStream.write()
data.bytes
[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)