Casting a pointer to UInt in Swift

October 16, 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!
}
Picture of me with a corgi

Noah Gilmore

Hello! I'm Noah, a software developer based in the San Francisco bay area. I focus mainly on iOS, Apple platform development, and full stack web development.

  • 💻 I'm writing a macOS editor for Atlassian Confluence called Fluency
  • 📱 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