Home > other >  Find the sum of an array in swift
Find the sum of an array in swift

Time:02-16

I have an array that holds integer values. And I have defined it like so:

@State private var numbers: Array = []

the array is updated as the user uses the app. At a certain point, I need to find the sum of all the values in the array. Here is what I tried to do:

let sumOfNum = numberz.reduce(0,  )

However, this is giving me the following error on the plus( ) symbol:

Cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Any) throws -> Int'

Not sure what the problem is. Any help or guidance would be appreciated.

CodePudding user response:

Your issue is probably your Array declaration. You should declare is as an array of Int instead of an array of Any.

enter image description here

So your array declaration should be

@State private var numbers: [Int] = []

CodePudding user response:

This error occurs what exactly users says in comment. You declared numbers as an Array that means numbers can have something like that [1,"bla bla",2.0,true] . It can get more than one collection type. Thats why you cannot use reduce directly. Its an Int future.

If you still want to numbers must be Array and dont want to give a spesific type, you must control it

var numbers: NSArray = []

if let intArray = numbers as NSArray as? [Int] {

    let sumOfNum = intArray.reduce(0,  )
}
  • Related