How can I read an item from a tuple based on a dynamic value? For example, if I want "banana" here I do this:
var tuple = ("banana", "sock", "shoe")
print(tuple.0)
But how can I use a value stored in another variable?
var parameter = 0
print(tuple.parameter)
Tuples aren't flexible enough to do this. You can come close with functions:
let tuple = ("banana", "sock", "shoe")
let first = { (t: (String, String, String)) -> String in t.0 }
let second = { (t: (String, String, String)) -> String in t.1 }
let third = { (t: (String, String, String)) -> String in t.2 }
let choice = first
print(first(tuple))
But this isn't scalable at all; you need a set of functions like this for every tuple type you want to interact with.
One option might be to create a struct as an alternative to your tuple. Then you can use a KeyPath. For example:
struct Items
{
let first: String
let second: String
let third: String
init(tuple: (String, String, String))
{
self.first = tuple.0
self.second = tuple.1
self.third = tuple.2
}
}
let choice = \Items.first
let items = Items(tuple: tuple)
print(items[keyPath: choice])
Or, if your tuples are all homogenous like your example, another option is to convert to an array and use array subscripting:
extension Array where Element == String
{
init(_ tuple: (String, String, String))
{
self.init([tuple.0, tuple.1, tuple.2])
}
}
let array = Array(tuple)
let index = 0
print(array[index])
(Subscript-like keypaths are also coming in future Swift, but they don't buy you anything in this case above a regular subscript.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With