C union type in Swift?

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

Well, there is no direct support of unions, in Swift, but we can use enumeration for our purpose.

Ex-

enum Algebra {
  case Addition(Double, Double)
  case Substraction(Double, Double)
  case Square(Double)

  var result : Double {
    switch(self)
    {
    case .Addition(let a, let b): return a + b
    case .Substraction(let a, let b):  return a - b
    case .Square(let a):  return a * a
    }
  }
}

let solution = Algebra.Addition(5, 3)
println(solution.result) //Output: 8.0

Tags:

C

Unions

Swift