Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Get an element from a tuple

Tags:

swift

tuples

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.

like image 647
Suragch Avatar asked May 13 '16 02:05

Suragch


People also ask

Is tuple value type Swift?

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.

Is tuple hashable Swift?

The reason that tuples cannot be used as keys (or specifically, are not hashable ) is because they are not strictly immutable.


2 Answers

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 
like image 71
Suragch Avatar answered Sep 21 '22 19:09

Suragch


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"] 
like image 41
Lumialxk Avatar answered Sep 23 '22 19:09

Lumialxk