如何计算自定义类型数组的各个变量的总和



我是Swift中编码的新手。我的目标是构建一个包含许多自定义类变量之和的变量。要说清楚:

我有一个名为";条目";其具有Double变量"0";sum";,例如50.00。

我使用ViewController让用户创建一个带有文本字段输入的新条目,尤其是新条目的总和。当按下相关按钮时,这个新的entry元素被附加到entry类型的数组中。

@IBAction func addEntry(_ sender: UIButton){
    // take user input
    let name = nameTextField.text ?? ""
    let sum = Double(sumTextField.text!) ?? 0.0
    let category = selectedCategory
    // save user input in new entry
    let newEntry = Entry(name: name, sum: sum, category: category)
    entries.append(newEntry)
    saveEntries()
    os_log("Saved new entry successfully.", log: OSLog.default, type: .debug)

在另一个ViewController中,我想访问数组";条目";并构建所有Entry元素的所有和变量的和,例如Entry 1的和+Entry 2的和+Item 3的和

我目前在编码方面的尝试如下:

var entriesDatabase = [Entry]()
//extract sum of entries and build sumOfEntries
    var sumArray = [Double]()
    for entry in entriesDatabase {
        sumArray.append(entry.sum)
    }
    sumOfEntries = sumArray.reduce(0, +)

第一个视图控制器中的条目数组是通过使用NSKeyedArchiver保存的,并由第二个视图控制器的NSKeyedUnarchiver.unarchiveObject(withFile:(加载,然后再调用上面的函数(我知道,该函数已被弃用,但它适用于我当前的目的(。

我使用print函数来隔离问题,据我所见,无论我创建了多少Entry元素,sumOfEntries始终保持0.0(不过这本身似乎很有效(。有人知道我做错了什么吗?

编辑:对我来说,问题似乎真的是计算不起作用,而不是将数据从一个视图传递到另一个视图。不知怎的,数组总是空的。数据的传输是通过将其永久保存在驱动器上,然后使用NSKeyedArchiver函数加载来完成的。为了清楚起见,请参阅以下代码:

/MARK: calculate and display balance
func calculate(){
    //load data from user defaults
    recurringCalculationValue = UserDefaults.standard.value(forKey: "recurringExpenses") ?? 0.0
    monthlyIncomeCalculationValue = UserDefaults.standard.value(forKey: "monthlyIncome") ?? 0.0
    
    //extract sum of entries and build sumOfEntries
    var sumArray = [Double]()
    for entry in entriesDatabase {
        sumArray.append(entry.sum)
    }
    sumOfEntries = sumArray.reduce(0, +)
    
    //cast the user defaults into Double
    let mICV = monthlyIncomeCalculationValue as! Double
    let rCV = recurringCalculationValue as! Double
    
    //convert the Strings to Double! and calculate balance
    balance = Double(mICV) - Double(rCV) - sumOfEntries
    
    //display balance in sumLabel
    sumLabel.text = "(balance)"
    
    //debugging
    print("balance = (balance)")
    print("sumOfEntries = (sumOfEntries)")
    print("monthlyIncomeCalculationValue = (monthlyIncomeCalculationValue)")
    print("recurringCalculationValue = (recurringCalculationValue)")
    print("UserDefault monthlyIncome = (String(describing: UserDefaults.standard.value(forKey: "monthlyIncome")))")
    print("UserDefault recurringExpenses = (String(describing: UserDefaults.standard.value(forKey: "recurringExpenses")))")
}
//this function is called when the ViewController is opened
@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
    //Load saved entries into entries array if entries were saved
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    if let pathComponent = url.appendingPathComponent("entries") {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            print("File available.")
            entriesDatabase = loadEntries()!
            print("Database loaded.")
        } else {
            print("File not available.")
        }
    } else {
        print("File path not available.")
    }
    
    calculate()
}
private func loadEntries() -> [Entry]?  {
       return NSKeyedUnarchiver.unarchiveObject(withFile: Entry.ArchiveURL.path) as? [Entry]
   }

我希望,这能让我的问题更清楚,再次感谢!

在我看来,在var entriesDatabase = [Entry]()中,您为类型为Entry的对象创建了一个新数组,它(当然(最初是空的。因此,这些值的总和将为0。

您想要的是缓存值,例如在saveEntries()-函数中。你可能想看看UserDefaults,它将信息存储在类似地图的物质中。

最新更新