Learn how Swift represents imported C structures and unions, including types with bitfields and unnamed fields.
Swift imports any C structure declared in a C header as a Swift structure. The imported Swift structure contains a stored property for each C structure field and an initializer whose parameters correspond to the stored properties.
Structures with Default Values
If all imported members have default values, Swift also provides a default initializer that takes no arguments. For example, given the following C structure:
When you import the Color structure, the Swift version is equivalent to the following:
Swift imports C unions as Swift structures. Although Swift doesn’t support natively declared unions, a C union imported as a Swift structure still behaves like a C union. For example, consider a C union named
Schroedingers that has an
is and an
In Swift, it’s imported like this:
Because unions in C use the same base memory address for all of their fields, all of the computed properties in a union imported by Swift use the same underlying memory. As a result, changing the value of a property on an instance of the imported structure changes the value of all other properties defined by that structure.
In the example below, changing the value of the
is computed property on an instance of the
Schroedingers structure also changes the value of the instance’s
is computed property:
Swift imports bit fields that are declared in structures, like those found in Foundation’s
NSDecimal type, as computed properties. When accessing a computed property corresponding to a bit field, Swift automatically converts the value to and from compatible Swift types.
Unnamed Structure and Union Fields
union types can define fields that have no name or that are of an unnamed type. Unnamed fields consist of a nested
union type with named fields.
For example, consider a C structure named
Cake that contains the fields
height nested within an unnamed union type, and a field
toppings of an unnamed struct type:
Cake structure has been imported, you can use the default initializer to create an instance and use it as follows:
Cake structure and its nested types are imported with a memberwise initializer that you can use to initialize the structure with custom values for its fields:
Because the first field of the
Cake structure is unnamed, its initializer’s first parameter doesn't have a label. Because the
Cake structure has fields with unnamed types, you use the
.init initializers (allowed due to Swift's type inference) to set the initial value for each of the structure’s unnamed fields.