有什么方法可以快速迭代元组? [英] Any way to iterate a tuple in swift?
问题描述
我很好奇如何快速使用元组进行 for 循环.
I am curious how to do a for loop with a tuple in swift.
我知道要访问每个成员,您可以使用索引号使用点表示法
I know that to access each member you can use dot notation using the index number
var tupleList = ("A",2.9,3,8,5,6,7,8,9)
for each in tupleList {
println(each)
}
//错误:类型不符合协议序列
//Error: Type does not conform to protocol sequence
推荐答案
是的,你可以!
func iterate<C,R>(t:C, block:(String,Any)->R) {
let mirror = reflect(t)
for i in 0..<mirror.count {
block(mirror[i].0, mirror[i].1.value)
}
}
瞧!
let tuple = ((false, true), 42, 42.195, "42.195km")
iterate(tuple) { println("\($0) => \($1)") }
iterate(tuple.0){ println("\($0) => \($1)")}
iterate(tuple.0.0) { println("\($0) => \($1)")} // no-op
注意最后一个不是元组,所以什么也不会发生(尽管它是一个 1 元组或单个",其内容可以被访问 .0
, reflect(it).count
为 0).
Note the last one is not a tuple so nothing happens (though it is a 1-tuple or "Single" which content can be accessed .0
, reflect(it).count
is 0).
有趣的是 iterate()
甚至可以迭代其他类型的集合.
What's interesting is that iterate()
can iterate even other types of collection.
iterate([0,1]) { println("\($0) => \($1)") }
iterate(["zero":0,"one":1]) { println("\($0) => \($1)") }
该集合包括 class
和 struct
!
struct Point { var x = 0.0, y = 0.0 }
class Rect { var tl = Point(), br = Point() }
iterate(Point()) { println("\($0) => \($1)") }
iterate(Rect()) { println("\($0) => \($1)") }
警告:作为块的第二个参数传递的值是 Any
类型.您必须将其转换回原始类型的值.
Caveat: the value passed as the 2nd argument of the block is type Any
. You have to cast it back to the values with original type.
这篇关于有什么方法可以快速迭代元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!