Search code examples
swifttuplesxcode6-beta5

Swift: How to better format the output when using println with a tuple?


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


Solution

  • 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()