How to find the sum of all elements of an NSMutableArray? Swift

Viewed 103

So I'm trying to make an NSMutableArray that can update when another viewcontroller has inputted values.

This other viewcontroller is our "AddNewViewController."

AddNewViewController.swift

nameArray.add(namestring)

minutesArray.add(minutesint!)


print(nameArray)
print(minutesArray)


UserDefaults.standard.set(nameArray.mutableCopy(), forKey: "namearray")
UserDefaults.standard.set(minutesArray.mutableCopy(), forKey: "minutesarray")
UserDefaults.standard.synchronize()

NameArray is irrelevant, uses an inputted string and adds that to our namearray.

The problem lies with minutesArray: I set an Int (minutesint) for minutesArray, which is inputted through a UITextField and converted into an int. This is then put into our UserDefaults for use in our other viewcontroller, ViewController

ViewController.swift

nameArray = UserDefaults.standard.mutableArrayValue(forKey: "namearray")
minutesArray = UserDefaults.standard.mutableArrayValue(forKey: "minutesarray")


let myCell = UITableViewCell()
myCell.textLabel?.text = ("Name: \(nameArray[indexPath.row] as! String)    Score (minutes): \(minutesArray[indexPath.row] as! Int)")

return myCell

I should clarify, that above is my cellForRowAt declaration. As you can see, it sets everything to our tableview just fine and dandy.

However, when I try and use tips from other questions such as using the "reduce" for an NSArray to sum all elements up I get this error from this piece of code:

let sumarray = minutesArray.reduce(0, +)
//Error: Ambiguous reference to member '+'

I realize that something is wrong with my formatting, because when I tested it with an immutable array like

let array = [1, 2 ,3]
let testarray = array.reduce(0, +)
print (testarray)

It gives me a nice, sexy print of 5?

When I checked the type that array is, it's apparently an [Int] type. However, I thought reduce was only possible to use on Arrays?

What am I doing wrong?

Can anyone point me in the right direction?

1 Answers

Read it as an int array [Int] instead

var minutesArray = UserDefaults.standard.array(forKey: "minutesarray") as? [Int] ?? [Int]()
Related