【问题标题】:Swift: how to count the number of elements in TupleSwift:如何计算元组中的元素数量
【发布时间】:2015-08-26 18:54:46
【问题描述】:

我想知道 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)

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

【问题讨论】:

标签: swift tuples


【解决方案1】:

在 Swift 3 中,您可以像这样计算元组中的元素数量:

let myTuple = (1,2,3,4)
let size = Mirror(reflecting: myTuple).children.count

【讨论】:

    【解决方案2】:

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

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

    要从元组中提取值,您可以使用 MirrorType。你可以找到更多here

    let tuple = (1, 2, 3)
    let count = Mirror(reflecting: tuple).children.count // 3
    

    【讨论】:

    • 谢谢你,这正是我所需要的。我很感激。 (顺便说一句。你和我的一个朋友同名,他实际上并不喜欢苹果,所以当我看到你的评论时,我就像“什么”)
    • 这似乎不适用于 Swift 5 等最近的 swift。error: Cannot find 'reclect' in scope
    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    相关资源
    最近更新 更多