Dynamic access of unnamed tuple fields

Is there any way to get an unnamed property of a tuple given its position?

Like below:

let record = ("field1", "field2")

func getRecordFieldValue(at: Int, of record: (String, String)) -> Any? {
    // pseudo code
    record.[at]
}
let record = ("field1", "field2")
print(record.0)

gives: "field1"

But you cannot write

let n = 0
record.n

I can propose this workaround. Hope it will help.

func getRecordFieldValue(at: Int, of record: (String, String)) -> Any? { 
    // pseudo code
    switch at {
    case 0: return record.0
    case 1: return record.1
    default: return nil
    }
}

let n = 1
print(getRecordFieldValue(at: n, of: record))

gives: Optional("field2")

Works with multiple types:

typealias MyTuple = (String, String, Int)
let record : MyTuple = ("field1", "field2", 3)

func getRecordFieldValue(at: Int, of record: MyTuple) -> Any? {
    // pseudo code
    switch at {
    case 0: return record.0
    case 1: return record.1
    case 2: return record.2
    default: return nil
    }
}

let n = 2
print(getRecordFieldValue(at: n, of: record))

gives: Optional(3)

In your example the tuple is homogeneous, that is, all the elements are of the same type (String). Can you guarantee that?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Dynamic access of unnamed tuple fields
 
 
Q