Casting a pointer to UInt in Swift

October 15, 2018

There are some times in Swift, like when using System Trace, that you want to get the pointer value of an object directly as a UInt (passing the pointer to kdebug_signpost is one). I was surprised at how hard it was to find documentation on how to get a Swift reference’s pointer value as a UInt. Here’s how to do it, using the UInt(bitPattern:) initializer:

_ = withUnsafePointer(to: myObject) { unsafePointer in
    let pointerValue = UInt(bitPattern: unsafePointer)
    // do whatever with pointerValue: it's a UInt!
}
Tweet This
Get New Posts Via Email
Picture of me with a corgi

Noah Gilmore

I'm Noah, a software developer based in the San Francisco Bay Area. I focus mainly on full stack web and iOS development

  • 💻 I co-founded Replo, a no-code platform for e-commmerce
  • ✍️ You can read technical posts on my blog
  • 📱 I wrote an app which lets you create transparent app icons called Transparent App Icons
  • 🧩 I made a puzzle game for iPhone and iPad called Trestle
  • 🎨 I wrote a CoreImage filter utility app for iOS developers called CIFilter.io
  • 👋 Please feel free to reach out on Twitter / 𝕏