reduce - Swift - Cleaner Syntax for Reducing an Array inside Guard -
i have uiview driven 2 arrays: [float]
"data" , [uicolor]
"colors". if view isn't given proper data displaying empty state, controlled guard statement see here:
private func unwrap() -> ([float], [uicolor]) { guard let data = data, !data.isempty, let colors = colors, data.count == colors.count else { return ([1], [uicolor.lightgray]) } // empty state let total = data.reduce(0) { $0 + $1 } if total == 0 { return ([1], [uicolor.lightgray]) } return (data, colors) }
i don't repetition of empty state return ([1], [uicolor.lightgray])
being used twice. i've tried add data.reduce call inside guard statement, like:
private func unwrap() -> ([float], [uicolor]) { guard let data = data, !data.isempty, let colors = colors, data.count == colors.count, data.reduce(0) { $0 + $1 } != 0 else { return ([1], [uicolor.lightgray]) } // empty state return (data, colors) }
...the compiler doesn't understand syntax
private func unwrap() -> ([float], [uicolor]) { guard let data = data, !data.isempty, let colors = colors, data.count == colors.count, let total = data.reduce(0) { $0 + $1 }, total != 0 else { return ([1], [uicolor.lightgray]) } // empty state return (data, colors) }
...the result of closure data.reduce(0) { $0 + $1 }
isn't optional can't included in guard declaration.
is there cleaner way this?
this simplified version:
private func unwrap() -> ([float], [uicolor]) { guard let data = data, let colors = colors, data.count == colors.count, data.reduce(0, +) != 0 else { return ([1], [uicolor.lightgray]) } // empty state return (data, colors) }
reduce can use float's + function, , reduce on empty data array 0, don't need check empty status.
Comments
Post a Comment