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.
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加