Any way to iterate a tuple in swift? -



Any way to iterate a tuple in swift? -

i curious how loop tuple in swift.

i know access each fellow member can utilize dot notation using index number

var tuplelist = ("a",2.9,3,8,5,6,7,8,9) each in tuplelist { println(each) }

//error: type not conform protocol sequence

yes, can!

func iterate<c,r>(t:c, block:(string,any)->r) { allow mirror = reflect(t) in 0..<mirror.count { block(mirror[i].0, mirror[i].1.value) } }

and voila!

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

note lastly 1 not tuple nil happens (though 1-tuple or "single" content can accessed .0, reflect(it).count 0).

what's interesting iterate() can iterate other types of collection.

iterate([0,1]) { println("\($0) => \($1)") } iterate(["zero":0,"one":1]) { println("\($0) => \($1)") }

and collection includes 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)") }

caveat: value passed 2nd argument of block type any. have cast values original type.

swift

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

c# - Create a Notification Object (Email or Page) At Run Time -- Dependency Injection or Factory -

Set Up Of Common Name Of SSL Certificate To Protect Plesk Panel -