If I have a tuple like this
var answer: (number: Int, good: Bool)
How do I get one of the elements?
This doesn't work:
answer["number"]
I am modeling this question after Swift: Get an array of element from an array of tuples, but my question was a little more basic. I did find the answer buried in the documentation so I am adding my answer below in Q&A format for faster searching in the future.
Types in Swift fall into one of two categories: first, “value types”, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple. The second, “reference types”, where instances share a single copy of the data, and the type is usually defined as a class.
The reason that tuples cannot be used as keys (or specifically, are not hashable ) is because they are not strictly immutable.
According to the documentation (scroll down to Tuples), there are three ways to do it.
Given
var answer: (number: Int, good: Bool) = (100, true)
Method 1
Put the element variable name within a tuple.
let (firstElement, _) = answer let (_, secondElement) = answer
or
let (firstElement, secondElement) = answer
Method 2
Use the index.
let firstElement = answer.0 let secondElement = answer.1
Method 3
Use the names. This only works, of course, if the elements were named in the Tuple declaration.
let firstElement = answer.number let secondElement = answer.good
I tried this. It's not so good but works...
protocol SubscriptTuple { associatedtype Tuple associatedtype Return var value: Tuple { get set } subscript(sub: String) -> Return? { get } } struct TupleContainer: SubscriptTuple { typealias Tuple = (number: Int, good: Bool) typealias Return = Any var value: Tuple subscript(sub: String) -> Return? { switch sub { case "number": return value.number case "good": return value.good default: return nil } } }
And this is how to use.
let answer = Answer(value: (120, false)) answer["number"]
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