如何将字符串转换为UnsafePointer 和长度
当我使用NSOutputStream
的write
方法时
func write(_ buffer: UnsafePointer<UInt8>, maxLength length: Int) -> Int
我不知道如何转换String
为UnsafePointer<UInt8>
和长度
如何迅速做到这一点?
回答:
您必须先将字符串转换为UTF-8数据
let string = "foo bar"let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
然后将其写入输出流
let outputStream: NSOutputStream = ... // the stream that you want to write tolet bytesWritten = outputStream.write(UnsafePointer(data.bytes), maxLength: data.length)
该UnsafePointer()
转换是必要的,因为data.bytes
有型UnsafePointer<Void>
,而不是UnsafePointer<UInt8>
如预期的write()
方法。
let string = "foo bar"// Conversion to UTF-8 data (cannot fail):
let data = string.data(using: String.Encoding.utf8)!
// Write to output stream:
let outputStream: NSOutputStream = ... // the stream that you want to write to
let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
以上是 如何将字符串转换为UnsafePointer 和长度 的全部内容, 来源链接: utcz.com/qa/406345.html