C unions in Xcode 7.1

I wanted to play with unions imported from C in Xcode 7.1 beta 2, but can't get it to work. This is what the relase notes say:


"Field getters and setters are now created for named unions imported from C. In addition, an initializer with a named parameter for the field is provided. (19660119)"


And here's what I did:

  • Create a OS X command line project in Xcode 7.1.
  • Create a new C file and add it to the project. Say yes when Xcode asks you to create a bridging header.
  • Add the following code to the C header (taken from the release notes):
typedef union IntOrFloat {
   int intField;
   float floatField;
} IntOrFloat;


  • Include the C header in the bridging header.
  • In main.swift, try to create a variable of the union type:
let x = IntOrFloat(intField: 10) // error: Extra argment 'intField' in call


According to the release notes, this should work, but it doesn't. If I look at the interface Swift generated for the C header, I get this:

public struct IntOrFloat {
    public init()
}


But it should look like this:

struct IntOrFloat {
   var intField: Int { get set }
   init(intField: Int)

   var floatField: Float { get set }
   init(floatField: Float)
}


I can use the union normally in C code and call that C code from Swift, so I'm not sure what I'm doing wrong. Is this not fully functional yet in beta 2?

Accepted Answer

Tested on Version 7.1 beta (7B75).

let x = IntOrFloat(intField: 10)
print(x.floatField) //->1.4013e-44


Generated Interface:

public struct IntOrFloat {
    public var intField: Int32
    public var floatField: Float
    public init(intField: Int32)
    public init(floatField: Float)
    public init()
}


I'm afraid you have mistakenly invoked another version of Xcode.

Just wanted to add a related question: Will the memory layout and size (in Swift) be the same as those of the C union?

I'm afraid you're right. I was so sure I had updated to beta 2 on this machine but apparently I hadn't. Sorry for that and thanks for trying this out for me.

Unable to confirm with all possible cases, but it's working with this simple case:

var x = IntOrFloat(intField: 10)
print(x.floatField) //->1.4013e-44
print(sizeofValue(x)) //->4
x.floatField = 1.0
print(String(x.intField, radix: 16)) //->3f800000 = 1.0 in IEEE 754 float(binary 32)
C unions in Xcode 7.1
 
 
Q