UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: ForEach with Math Increment

Forums > SwiftUI

Building a custom mortgage calculator. I have the main view functioning completely. I have a NavigationLink to a List view that breaks out each payment into principal and interest. I am successfully casting the list based on the amount of payments ie. 10yr -> 120 rows, 15yr -> 180 rows etc. My struggle is figuring out how to decrement the currentBalance by a math function each row. Basically it needs to be Row 1 = currentBalance (.04/12), then in Row 2, I need to take the new currentBalance (.04/12). Keep doing that same math function to the final row which will show the amount of interest paid each payment to decrase until the final payment. The below is obiously just showing the currentBalance as the same in each row. Thanks for any input. I can upload the full ContentView if anyone would like to check it out.

NavigationLink("Payment Breakdown", destination: List {
                    ForEach((1...rows), id: \.self) {
                        Text("Mo. \($0):   \((self.currentBalance), specifier: "%.2f")")
                    }
                })

2      

Create a function that takes as parameters the starting balance and the number of years and retuns an array with the payment amounts. Loop through that array to build your List.

Something like this...

func calculatePaymentSchedule(forAmount startingBalance: Double, overYears numberOfYears: Int) -> [Double] {
    //...do your calculations and return an array of amounts
}

var body: some View {
    let payments = calculatePaymentSchedule(forAmount: 180_000, overYears: 2)
    return NavigationLink("Payment Breakdown", destination: List {
        ForEach(0..<payments.count) { idx in
            Text("Mo. \(idx + 1):   \((payments[idx]), specifier: "%.2f")")
        }
    })
}

(Done off the top of my head and untested, so it may not work 100% for your needs, but you should be able to muck around with it to get what you want.)

I would even suggest pulling these calculations out of the NavigationLink like you have theme here and creating a new View with properties for the initial amount and the length of time. Then you can calculate them when the View appears and load them into a List.

2      

After racking my brain for several days, and landing somewhere near the end of the internet, here is where I ended up. Keep in mind, I can fudge my way around some code, but am by no means a software engineer. Just a hobby of mine. Some may laugh at the simplicity, but maybe it will help someone somewhere. Thanks for helping!

    var payments: [Double] {
        var intSchedule = [Double]()
        let pmt = monthlyPayment
        var bal = currentBalance

        while bal > 0 {
            let intr = bal * interestRateMo
            bal = bal - (pmt - intr)
            intSchedule.append(intr)
        }
        return(intSchedule)
    }

        NavigationLink("Payment Breakdown", destination: List {
                      ForEach((0...rows), id: \.self) {
                                  Text("Mo. \($0 + 1) - Interest:   $\((self.payments[$0]), specifier: "%.2f")")

                      }

        })

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.