Swift: Accessing tuples by index

Let's say I have this code:

let tuples = ("1", 2, "3", "4", "5", "6", "7", false)

func tableView(tableView:NSTableView, viewForTableColumn tableColumn:NSTableColumn?, row:Int) -> NSView?
{
    let valueForView = tuples[row]
}

Is there a way to access tuples by index?

+4
source share
4 answers

What you want is not possible with tuples, and if you don't want to drop everything later, the only option is a struct or class. struct looks like the best choice :)

struct MyStruct {
    let opt1 = 0
    let opt2 = 0
    let opt3 = 0
    ...
    let boolThing = false
}
0
source

No, you can only access tuple elements by directly specifying an index, for example.

tuples.5

For your purpose, you just need to use an array.

+6
source

, . , , , . , , , , .

struct TupleWrapper {
    let tuple: (String, Int, String, String, String, String, String, Bool)    
    let count: Int
    private let mirrors: [MirrorType]

    subscript (index: Int) -> Any {
        return mirrors[index].value
    }

    init(tuple: (String, Int, String, String, String, String, String, Bool)) {
        self.tuple = tuple

        var mirrors = [MirrorType]()
        let reflected = reflect(tuple)

        for i in 0..<reflected.count {
            mirrors.append(reflected[i].1)
        }

        self.mirrors = mirrors
        self.count = mirrors.count
    }
}

let wrapper = TupleWrapper(tuple: ("1", 2, "3", "4", "5", "6", "7", false))
wrapper[0] // "1"
wrapper[wrapper.count - 1] // false

The above code uses the Swift display APIs to get the logical children of your tuple and add their mirrors to an array on which we can index for each value of the mirror. This is pretty straight forward, but, as you would expect, since we work with tuples, it can in no way be dynamic. A wrapper must be made for a specific type of tuple.

For some related readings, see a recent NSHipster MirrorType article .

+4
source

This is possible using reflection:

Mirror(reflecting: tuples).children[AnyIndex(row)].value
+1
source

All Articles