generics - Swift create function closure with shortened dollar sign syntax support -
i've added extension array
extension array { func each(call: (element: element, idx: int) -> ()) { (idx, element) in enumerate(self) { call(element: element, idx: idx) } } }
it's shortcut for in enumerate
. use i'd call this
[1, 2, 3, 4].each { element, idx in print(element) return }
this print 1234
works, i'd rather not require return
. when tried in playground without return prints "0 elements" 4 times rather printing value.
my goal extension make work map function, short , easy apply function array, in case call function on each element without mutating original.
[1, 2, 3, 4].map { $0 * 2 } //converts array [2, 4, 6, 8]
each can accomplished calling
[1, 2, 3, 4].each { print($0); return }
this works, rather returning element $0
returns tuple (element, idx)
. use pretty using $0.0
element , $0.1
index, feels clunky. i'd prefer use $0
element , $1
index shortened syntax. i'd prevent return being necessary.
so in summary, i'd clean closure shortened $
syntax making $0
first argument returned , $1
second element, , i'd make return
unnecessary when calling function println
.
swift 2.0 have expression built in, if want write yourself, it's simple
extension collectiontype { func each(@noescape expression: (self.generator.element, int) -> ()) { item in self { expression(item) } } }
and index:
extension collectiontype { func each(@noescape expression: (self.generator.element, int) -> ()) { (i, item) in self.enumerate() { expression(item, i) } } }
by extending collectiontype
works on both array
, other collections, such set
.
Comments
Post a Comment