Writing Data to an NSOutputStream in Swift 3

后端 未结 4 959
谎友^
谎友^ 2020-12-14 04:37

The solution of this question no longer works with Swift 3.

There is no longer a property bytes of Data (formerly NSData.

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 05:11

    Data and NSData are two separate classes in Swift 3, and Data does not have the bytes property.

    The solution is to define data as being of type NSData

    let data: NSData = dataToWrite.first!
    self.outputStream.write(UnsafePointer(data.bytes), maxLength: data.length)
    

    According to Migrating to Swift 2.3 or Swift 3 from Swift 2.2:

    The migrator will convert most uses of NSData to the new value type Data. However, there are certain methods on NSData that operate on UnsafeMutablePointer, while the corresponding methods on Data use UnsafeMutablePointer. (For example, NSData.getBytes(:length:) is more accepting than Data.copyBytes(:length:).) As a reminder, the in-memory layout of Swift types is not guaranteed.

提交回复
热议问题