Swift passing calculated data back to previous view controller

You could possibly also use an unwind segue to pass back the data.


My suggestion is to use a callback closure. It's less code and easier to handle than protocol / delegate.

In AddSubtractMoney declare a callback variable and call it in sendBackUpdatedNumber passing the Double value

class AddSubtractMoney: UIViewController {

   // ...

    var callback : ((Double)->())?

  // ...

    func sendBackUpdatedNumber(){

        let newestUpdate = UserInfo(whatYouSpentToday: runningNumber, oldDailyBudgetPassed: dailyBudgetPassedThrough)
        amountPassedBackToUserInfo = dailyBudgetPassedThrough - Double(runningNumber)!
        newestUpdate.goalToSaveDaily = amountPassedBackToUserInfo
        print(amountPassedBackToUserInfo)
        callback?(amountPassedBackToUserInfo)
    }
}

In prepare(for segue assign the closure to the callback variable and add the code to be executed on return

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "addOrSubtractMoney"{
        let addOrSubtractMoneyVC = segue.destination as! AddSubtractMoney
        addOrSubtractMoneyVC.callback = { result in
             print(result)
            // do something with the result
        }
        addOrSubtractMoneyVC.dailyBudgetPassedThrough = userDailyBudgetPassedOver
    }
}

Using delegate

if segue.identifier == "addOrSubtractMoney" {

    let addOrSubtractMoneyVC = segue.destination as! AddSubtractMoney

        addOrSubtractMoneyVC.dailyBudgetPassedThrough = userDailyBudgetPassedOver

       addOrSubtractMoneyVC.delegate = self
    }
}

You need to add delegate property in AddSubtractMoney class

var delegate: AddSubtractMoneyDelegate?

Create Protocol in AddSubtractMoney class

protocol AddSubtractMoneyDelegate {
  func calculatedValue(value: Double)
}

And respond to delegate

 func sendBackUpdatedNumber(){

    let newestUpdate = UserInfo(whatYouSpentToday: runningNumber, oldDailyBudgetPassed: dailyBudgetPassedThrough)

   amountPassedBackToUserInfo = dailyBudgetPassedThrough - Double(runningNumber)!
   newestUpdate.goalToSaveDaily = amountPassedBackToUserInfo

    print(amountPassedBackToUserInfo)

    self.delegate.calculatedValue(value: amountPassedBackToUserInfo)
}

Now you need to implement this delegate method in class where delegate is set.

Here in UserInfoViewController class delegate is set so you need to implement its delegate method

extension UserInfoViewController: AddSubtractMoneyDelegate {

  func calculatedValue(value: Double) {

       //set label here
  } 

}