swift - Why does reduce not work on Struct? -
i have following code
struct tab { var origin:cgfloat var width:cgfloat init(width:cgfloat) { origin = 0 self.width = width } } let subtabs = [tab(width:1), tab(width:2)] let w = reduce(subtabs, cgfloat(0), { $0.width + $1.width })
and expect reduce
sum width
s in struct. raises compiler error (you can test in playground).
the function reduce needs takes 2 arguments: accumulated value , next item in sequence. function expecting 2 sequence items (tab
structs). since returning float, accumluted value float, , not tab
expect. correct call is:
let w = reduce(subtabs, cgfloat(0), { $0 + $1.width })
Comments
Post a Comment