Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: how to count the number of elements in Tuple

Tags:

swift

tuples

I was wondering if there is a method or function in Swift which can count the number of elements in the tuple.

Reason of question:

  1. I have a tuple called "tople"
  2. What I want to do is to load the elements into variables (by using for loop, where you actually need the number of elements)
  3. And then use this in a function.

Additional questions, can you use tuples to load variables into the function and/or to return them from a function?

var tople = (1,2,3)

func funkce (a:Int, b:Int, c: Int){

    println(a)
    println(b)
    println(c)
}


funkce(a,b,c)

Thanks and I do appreciate any helpful comment.

like image 758
aster007 Avatar asked Dec 05 '22 02:12

aster007


2 Answers

In Swift 3 you count the number of elements in a tuple like this:

let myTuple = (1,2,3,4)
let size = Mirror(reflecting: myTuple).children.count
like image 188
Teo Sartori Avatar answered Apr 10 '23 00:04

Teo Sartori


Yes, you can load tuples into variables.

let (a, b, c) = (1, 2, 3)

To extract values from a tuple, you can use MirrorType. You can find more here.

let tuple = (1, 2, 3)
let count = Mirror(reflecting: tuple).children.count // 3
like image 37
Tomáš Linhart Avatar answered Apr 09 '23 23:04

Tomáš Linhart