Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
Computed property to sum numeric arrays in Swift

Task from book says: without calling reduce(_: _:) method, sum sequences of numbers by adding a computed property called sum. You should be able to use it like this:

[3, 7, 7].sum            // 17
[8.5, 1.1, 0.1].sum      // 9.7

Hint by authors: in developer documentation check what protocols do Int and Double conform to, and what protocols do those protocols inherit from. Within below code I just kind of combined two solutions I found, however it still contains method reduce. If you can help me to understand how this can be solved / which part of developer documentation provides a clue. Also how can I avoid error in current code / apply possible solution on closed range.

extension Sequence where Element: Numeric {
    var sum: Any {
        return reduce(0, +)
    }
}

[3, 7, 7].sum
[8.5, 1.1, 0.1].sum
[1...4].sum // Error: Property 'sum' requires that 'ClosedRange<Int>' conform to 'Numeric'
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

[1...4].sum is working on an Array of ClosedRange ([...] mean "Array of..."). You meant: (1...4).sum.

You also mean:

   var sum: Element { ... }

rather than Any.

If you want to make it even more generic, you can move from Numeric up to AdditiveArithmetic this way:

extension Sequence where Element: AdditiveArithmetic {
    var sum: Element { reduce(.zero, +) }
}

That way it could work on things like vectors.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda