---
title: "#189: Interacting with C Variables \u0026 Pointers in Swift 🤓"
url: https://littlebitesofcocoa.com/189-interacting-with-c-variables-pointers-in-swift
author: Jake Marsh
published: 2016-02-11
topics: ["Swift","Techniques"]
description: "Most Swift developers are familiar with how great Swift is at integrating with Objective-C, but what about C itself?"
---

# #189: Interacting with C Variables & Pointers in Swift 🤓

By Jake Marsh, February 11, 2016. HTML: https://littlebitesofcocoa.com/189-interacting-with-c-variables-pointers-in-swift

Most **Swift** developers are familiar with how great **Swift** is at integrating with **Objective-C**, but what about **C** itself? Today we'll look at how we can interact with **C** variables and pointers in **Swift**. Let's dive in.

Here's a few variables in **C**:

``` c
const int *someInt
int *anotherInt
struct Spaceship *spaceship
```

When referenced in **Swift**, these become:

``` swift
UnsafePointer<Int>
UnsafeMutablePointer<Int>
COpaquePointer
```

What about those pesky **void pointers** in **C**?

``` c
void launchSpaceshipWithID(const void *spaceshipID);
```

Buckle up, for this we'll need to go <i>unsafe...</i>

Swift tries its best to keep us safe, so for something like void pointers, we'll need to jump through a few safety-defying hoops:

``` swift
var sID = 31
withUnsafePointer(&sID) { (p: UnsafePointer<Int>) in
  let voidP = unsafeBitCast(p, UnsafePointer<Void>.self)
  launchSpaceshipWithID(voidP)
}
```

First we create a regular `Int` value in **Swift**.  Nothing special. Then, we'll pass it in to the `withUnsafePointer` **function**, along with a **closure**. Inside, we'll be passed in an UnsafePointer version of our original Int. We'll use the `unsafeBitCast` **function** to convert it into to a void pointer. Finally, we'll pass it in the **C function**. Whew!
