iOS Developer Library — Pre-Release

Developer

Using Swift with Cocoa and Objective-C

iBooks
On This Page

Interacting with C APIs

As part of its interoperability with Objective-C, Swift maintains compatibility with a number of C language types and features. Swift also provides a way of working with common C constructs and patterns, in case your code requires it.

Primitive Types

Swift provides equivalents of C primitive integer types—for example, char, int, float, and double. However, there is no implicit conversion between these types and core Swift integer types, such as Int. Therefore, use these types if your code specifically requires them, but use Int wherever possible otherwise.

C Type

Swift Type

bool

CBool

char, signed char

CChar

unsigned char

CUnsignedChar

short

CShort

unsigned short

CUnsignedShort

int

CInt

unsigned int

CUnsignedInt

long

CLong

unsigned long

CUnsignedLong

long long

CLongLong

unsigned long long

CUnsignedLongLong

wchar_t

CWideChar

char16_t

CChar16

char32_t

CChar32

float

CFloat

double

CDouble

Enumerations

Swift imports as a Swift enumeration any C-style enumeration marked with the NS_ENUM macro. This means that the prefixes to enumeration value names are truncated when they are imported into Swift, whether they’re defined in system frameworks or in custom code. For example, see this Objective-C enumeration:

Objective-C

  • typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
  • UITableViewCellStyleDefault,
  • UITableViewCellStyleValue1,
  • UITableViewCellStyleValue2,
  • UITableViewCellStyleSubtitle
  • };

In Swift, it’s imported like this:

Swift

  • enum UITableViewCellStyle: Int {
  • case Default
  • case Value1
  • case Value2
  • case Subtitle
  • }

When you refer to an enumeration value, use the value name with a leading dot (.).

Swift

  • let cellStyle: UITableViewCellStyle = .Default

Swift also imports options marked with the NS_OPTIONS macro. Whereas options behave similarly to imported enumerations, options can also support some bitwise operations, such as &, |, and ~.

In Objective-C, you represent an empty option set with the constant zero (0). In Swift, use nil to represent the absence of any options. For example:

Swift

  • let myString = myData.base64EncodedStringWithOptions(nil)

Pointers

Whenever possible, Swift avoids giving you direct access to pointers. There are, however, various pointer types available for your use when you need direct access to memory. The following tables use Type as a placeholder type name to indicate syntax for the mappings.

For return types, variables, and arguments, the following mappings apply:

C Syntax

Swift Syntax

const Type *

UnsafePointer<Type>

Type *

UnsafeMutablePointer<Type>

For class types, the following mappings apply:

C Syntax

Swift Syntax

Type * const *

UnsafePointer<Type>

Type * __strong *

UnsafeMutablePointer<Type>

Type **

AutoreleasingUnsafeMutablePointer<Type>

Constant Pointers

When a function is declared as taking a UnsafePointer<Type> argument, it can accept any of the following:

  • nil, which is passed as a null pointer

  • An UnsafePointer<Type>, UnsafeMutablePointer<Type>, or AutoreleasingUnsafeMutablePointer<Type> value, which is converted to UnsafePointer<Type> if necessary

  • An in-out expression whose operand is an lvalue of type Type, which is passed as the address of the lvalue

  • A [Type] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call

If you have declared a function like this one:

Swift

  • func takesAPointer(x: UnsafePointer<Float>) { /*...*/ }

You can call it in any of the following ways:

Swift

  • var x: Float = 0.0
  • var p: UnsafePointer<Float> = nil
  • takesAPointer(nil)
  • takesAPointer(p)
  • takesAPointer(&x)
  • takesAPointer([1.0, 2.0, 3.0])

When a function is declared as taking a UnsafePointer<Void> argument, it can accept the same operands as UnsafePointer<Type> for any type Type.

If you have declared a function like this one:

Swift

  • func takesAVoidPointer(x: UnsafePointer<Void>) { /* ... */ }

You can call it in any of the following ways:

Swift

  • var x: Float = 0.0, y: Int = 0
  • var p: UnsafePointer<Float> = nil, q: UnsafePointer<Int> = nil
  • takesAVoidPointer(nil)
  • takesAVoidPointer(p)
  • takesAVoidPointer(q)
  • takesAVoidPointer(&x)
  • takesAVoidPointer(&y)
  • takesAVoidPointer([1.0, 2.0, 3.0] as [Float])
  • let intArray = [1, 2, 3]
  • takesAVoidPointer(intArray)

Mutable Pointers

When a function is declared as taking an UnsafeMutablePointer<Type> argument, it can accept any of the following:

  • nil, which is passed as a null pointer

  • An UnsafeMutablePointer<Type> value

  • An in-out expression whose operand is a stored lvalue of type Type, which is passed as the address of the lvalue

  • An in-out [Type] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call

If you have declared a function like this one:

Swift

  • func takesAMutablePointer(x: UnsafeMutablePointer<Float>) { /*...*/ }

You can call it in any of the following ways:

Swift

  • var x: Float = 0.0
  • var p: UnsafeMutablePointer<Float> = nil
  • var a: [Float] = [1.0, 2.0, 3.0]
  • takesAMutablePointer(nil)
  • takesAMutablePointer(p)
  • takesAMutablePointer(&x)
  • takesAMutablePointer(&a)

When a function is declared as taking an UnsafeMutablePointer<Void> argument, it can accept the same operands as UnsafeMutablePointer<Type> for any type Type.

If you have declared a function like this one:

Swift

  • func takesAMutableVoidPointer(x: UnsafeMutablePointer<Void>) { /* ... */ }

You can call it in any of the following ways:

Swift

  • var x: Float = 0.0, y: Int = 0
  • var p: UnsafeMutablePointer<Float> = nil, q: UnsafeMutablePointer<Int> = nil
  • var a: [Float] = [1.0, 2.0, 3.0], b: [Int] = [1, 2, 3]
  • takesAMutableVoidPointer(nil)
  • takesAMutableVoidPointer(p)
  • takesAMutableVoidPointer(q)
  • takesAMutableVoidPointer(&x)
  • takesAMutableVoidPointer(&y)
  • takesAMutableVoidPointer(&a)
  • takesAMutableVoidPointer(&b)

Autoreleasing Pointers

When a function is declared as taking an AutoreleasingUnsafeMutablePointer<Type>, it can accept any of the following:

  • nil, which is passed as a null pointer

  • An AutoreleasingUnsafeMutablePointer<Type> value

  • An in-out expression, whose operand is primitive-copied to a temporary nonowning buffer. The address of that buffer is passed to the callee, and on return, the value in the buffer is loaded, retained, and reassigned into the operand.

Note that this list does not include arrays.

If you have declared a function like this one:

Swift

  • func takesAnAutoreleasingPointer(x: AutoreleasingUnsafeMutablePointer<NSDate?>) { /* ... */ }

You can call it in any of the following ways:

Swift

  • var x: NSDate? = nil
  • var p: AutoreleasingUnsafeMutablePointer<NSDate?> = nil
  • takesAnAutoreleasingPointer(nil)
  • takesAnAutoreleasingPointer(p)
  • takesAnAutoreleasingPointer(&x)

Types that are pointed to are not bridged. For example, NSString ** comes over to Swift as AutoreleasingUnsafeMutablePointer<NSString?>, not AutoreleasingUnsafeMutablePointer<String?>.

Function Pointers

C function pointers are imported into Swift as CFunctionPointer<Type>, where Type is a Swift function type. For example, a function pointer that has the type int (*)(void) in C is imported into Swift as CFunctionPointer<() -> Int32>.

Global Constants

Global constants defined in C and Objective-C source files are automatically imported by the Swift compiler as Swift global constants.

Preprocessor Directives

The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.

Simple Macros

Where you typically used the #define directive to define a primitive constant in C and Objective-C, in Swift you use a global constant instead. For example, the constant definition #define FADE_ANIMATION_DURATION 0.35 can be better expressed in Swift with let FADE_ANIMATION_DURATION = 0.35. Because simple constant-like macros map directly to Swift global variables, the compiler automatically imports simple macros defined in C and Objective-C source files.

Complex Macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

Build Configurations

Swift code and Objective-C code are conditionally compiled in different ways. Swift code can be conditionally compiled based on the evaluation of build configurations. Build configurations include the literal true and false values, command line flags, and the platform-testing functions listed in the table below. You can specify command line flags using -D <#flag#>.

Function

Valid arguments

os()

OSX, iOS

arch()

x86_64, arm, arm64, i386

A simple conditional compilation statement takes the following form:

  • #if build configuration
  •     statements
  •     #else
  • statements
  • #endif

The statements consist of zero or more valid Swift statements, which can include expressions, statements, and control flow statements. You can add additional build configuration requirements to a conditional compilation statement with the && and || operators, negate build configurations with the ! operator, and add condition blocks with #elseif:

  • #if build configuration && !build configuration
  •     statements
  •     #elseif build configuration
  •     statements
  •     #else
  • statements
  • #endif

In contrast with condition compilation statements in the C preprocessor, conditional compilation statements in Swift must completely surround blocks of code that are self-contained and syntactically valid. This is because all Swift code is syntax checked, even when it is not compiled.