2

I have defined this function:

func need_rebalance() -> (Bool, RebalanceStrategy) {

}

where RebalanceStrategy is an enum type

enum RebalanceStrategy: String {
    case LeftRight = "LeftRight"
    case RightLeft = "RightLeft"
}

When I tried to print it this way,

    println("Need rebalance? \(self.need_rebalance())")

I got output like this:

Need rebalance? (false, (Enum Value))

My questions are:

1) Is there an easy to extract a value from a tuple? (Hopefully something similar to python e.g. self.need_rebalance()[1]. Apparently this syntax does not work in swift because tuple does not support subscript())

2) How can I print the raw value of enum instead of having (Enum Value)?

I am using XCode6 Beta5

Imanou Petit
  • 89,880
  • 29
  • 256
  • 218
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304

2 Answers2

2

There's a way to extract the value using tuple indexes, but it's not nice, it involves reflect:

let tuple = self.need_rebalance()
let reflection = reflect(tuple)
reflection[0].1.value // -> true
reflection[1].1.value // -> RebalanceStrategy.?

Also, if your tuple members are not named:

let tuple = self.need_rebalance()
tuple.0 // -> true
tuple.1 // -> RebalanceStrategy.?

To access the raw value in an enum:

RebalanceStrategy.LeftRight.toRaw()
pNre
  • 5,376
  • 2
  • 22
  • 27
1

Use .0, .1 and so on to get the respective value from an unnamed tuple.

To get the raw value of the enum, use .toRaw()

var tuple = self.need_rebalance()

println("Need rebalance? \(tuple.0),\(tuple.1.toRaw())")

Better still, use a named tuple like this:

var tuple : (boolValue : Bool, enumValue :RebalanceStrategy) = self.need_rebalance()

println("Need rebalance? \(tuple.boolValue),\(tuple.enumValue.toRaw())")
aksh1t
  • 5,410
  • 1
  • 37
  • 55