cswiftunions

C union type in Swift?


How can I declare and use a C union type in Swift?

I tried:

var value: union {
      var output: CLongLong
      var input: [CInt]
    }

but it does not work...

UPDATED: I want to use union to split a 8 bytes number to 2 x 4 bytes number.


Solution

  • As the Apple Swift document , Enumerations can do similar thing and more.

    Alternatively, enumeration members can specify associated values of any type to be stored along with each different member value, much as unions or variants do in other languages. You can define a common set of related members as part of one enumeration, each of which has a different set of values of appropriate types associated with it.

    1) If you just want to split a 8 bytes number to 2 x 4 bytes numbers, as you might have known, the Bitwise Operation of Swift could help. Just like

    let bigNum: UInt64 = 0x000000700000008 //
    let rightNum = (bigNum & 0xFFFFFFFF) // output 8
    let leftNum = (bigNum >> 32)  // output 7
    

    2) If you want to simulate the union behaviour like C language, I tried a way like this. Although it works, it looks terrible.

    enum Number {
        case a(Int)
        case b(Double)
    
        var a:Int{
            switch(self)
            {
            case .a(let intval): return intval
            case .b(let doubleValue): return Int(doubleValue)
            }
        }
    
        var b:Double{
            switch(self)
            {
            case .a(let intval): return Double(intval)
            case .b(let doubleValue): return doubleValue
            }
        }
    }
    let num = Number.b(5.078)
    
    println(num.a)  // output 5
    println(num.b)  // output 5.078