Writing a String to an NSOutputStream in Swift

后端 未结 3 1781
抹茶落季
抹茶落季 2020-12-03 08:38

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

<
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 09:13

    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, but NSOutputStream.write() takes an UnsafePointer. Luckily, UnsafePointer has a way to convert between types:

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

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

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

提交回复
热议问题