1
\$\begingroup\$

I wrote the following in Swift to perform a sum:

let total:Double = session.courses.reduce(0) { $0 + $1.totalPrice() }

It's concise, it does the job but it does not seems very readable to me. Wouldn't a "classic"for loop be more explicit/readable/maintainable?

var total:Double = 0for dish in session.courses {    total += dish.totalPrice()}

Should closures always be the way to go in Swift?

askedJan 12, 2018 at 10:24
Arnaud's user avatar
\$\endgroup\$
0

2 Answers2

2
\$\begingroup\$

Both solutions are correct. Some advantages of the "functional" approachwithreduce():

  • Concise code.
  • Returns aconstant. It is clear to the reader thattotal is assigned to exactly once, and the compiler may use thisinformation for optimizing code.
  • The type annotation on the result value is not needed:

    let total = session.courses.reduce(0) { $0 + $1.totalPrice() }

    because that can be inferred from the compiler automatically.This will continue to compile without changes if the type oftotalPrice() is changed, e.g. fromDouble toFloat.

To increase legibility, you can use named closure parameters insteadof the$n shortcuts:

let total = session.courses.reduce(0) { (partialSum, dish) in    partialSum + dish.totalPrice()}
answeredJan 12, 2018 at 10:59
Martin R's user avatar
\$\endgroup\$
1
  • 1
    \$\begingroup\$+1 for legibility! I find the$n shortcuts incredibly hard to read, and they offer no information on what the values represent.\$\endgroup\$CommentedJan 17, 2018 at 3:18
2
\$\begingroup\$

Another alternatives:

let sum = session.courses.map({$0.totalPrice()}).reduce(0, +)

Another note, I think it's more elegant to implementtotalPrice as computed variable instead of function.

Another way is to useforEach :

var sum = 0session.courses.forEach {sum+=$0.totalPrice()}

as @Martin R mentioned the functional approach has some advantages especially that the result is constant.

answeredJan 16, 2018 at 20:25
iOSGeek's user avatar
\$\endgroup\$

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.