LoginSignup
16
13

More than 3 years have passed since last update.

Swift5 での Data.withUnsafeBytes

Last updated at Posted at 2019-04-18

前提

Double の連続のデータが Data の中にあるとしてそれを [ Double ] にしたいとします。

let d: Data ....

Swift5 より前

withUnsafeBytes$0UnsafePointer<ContentType> だったので以下のような感じだったのですが、これは swift5 で deprecated になりました。

Array(
    UnsafeBufferPointer( 
        start   : d.withUnsafeBytes{ p -> UnsafePointer< Double > in p }
    ,   count   : d.count / 8
    )
)

Swift5 以降

withUnsafeBytes$0UnsafeRawBufferPointer になったので、以下のような感じがいけます。

d.withUnsafeBytes{
    Array(
        UnsafeBufferPointer( 
            start   : $0.baseAddress!.assumingMemoryBound( to: Double.self )
        ,   count   : $0.count / 8
        )
    )
}

とか

Array(
    d.withUnsafeBytes{
        UnsafeBufferPointer( 
            start   : $0.baseAddress!.assumingMemoryBound( to: Double.self )
        ,   count   : $0.count / 8
        )
    }
)

メリット

クロージャの中でデータの count が取れるので、Data を保持するための変数(ここでは d )を定義せずに以下のように書けるようになりました。

Data( ... ).withUnsafeBytes ...

補足

ちなみに、最初のデータひとつだけが必要なのであれば、以下の書き方ができます。

d.withUnsafeBytes { $0.load( as: Double.self ) }
16
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
13