Swift:如何计算元组中的元素数量

ast*_*007 1 tuples swift

我想知道Swift中是否有方法或函数可以计算元组中元素的数量.

问题原因:

  1. 我有一个名为"tople"的元组
  2. 我想要做的是将元素加载到变量中(通过使用for循环,您实际需要元素的数量)
  3. 然后在函数中使用它.

还有其他问题,您可以使用元组将变量加载到函数中和/或从函数返回它们吗?

var tople = (1,2,3)

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

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


funkce(a,b,c)
Run Code Online (Sandbox Code Playgroud)

谢谢,我非常感谢任何有用的评论.

Teo*_*ori 6

在Swift 3中,你可以计算元组中元素的数量,如下所示:

let myTuple = (1,2,3,4)
let size = Mirror(reflecting: myTuple).children.count
Run Code Online (Sandbox Code Playgroud)


Tom*_*art 5

是的,您可以将元组加载到变量中.

let (a, b, c) = (1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

要从元组中提取值,可以使用MirrorType.你可以在这里找到更多.

let tuple = (1, 2, 3)
let count = reflect(tuple).count // 3
Run Code Online (Sandbox Code Playgroud)