16
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnsafeMutableRawPointer から UnsafeMutablePointer<T> にキャストする方法

Last updated at Posted at 2016-09-27

UnsafeMutableRawPointer から UnsafeMutablePointer<T> にキャストする方法をずっと悩んでいましたが、やっとわかったので、ここにメモしておきます。

わざとらしいコードですが、一旦 UnsafeMutableRawPointer にしたポインタを UnsafeMutablePointer<T> にキャストして、pointee を更新する事で、オリジナルも更新された事がわかります。Playground でも動作します。

.swift
// Swift 3.0 - Playground Ready
struct Context {
	var city = "Tokyo"
}

var context: Context = Context()
let rawPtr = UnsafeMutableRawPointer(&context)
let opaquePtr = OpaquePointer(rawPtr)
let contextPtr = UnsafeMutablePointer<Context>(opaquePtr)

context.city // "Tokyo"
contextPtr.pointee.city = "New York"
context.city // "New York"
16
13
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?