Home > Software design >  SwiftUI - Working with rows & columns in a matrix
SwiftUI - Working with rows & columns in a matrix

Time:03-11

I've created a Core Data entity with the following attributes:

And I've managed to manually enter 5 instances of "Round" so that I have 5 "rows" of data and have confirmed that Core Data is working.

Question is how to now add up the "columns" in the matrix (for the Int64 values), to then divide by number of "rows", i.e., to calculate the average for each column?

I'm a newbie, so any help appreciated.

Also, if I create a func to perform those calculations, can I merely call it immediately after the Core Data FetchRequest?

Thanks.

CodePudding user response:

Yes, you can create functions in your code and call them on the fetched core data. Also you would not need the total attribute in core data as you can calculate it on the fly.

I am assuming your FetchRequest generates an Array of Round called coredata

func total(round: Round) -> Int64 {
    return round.pos1   round.pos2   round.pos3   round.pos4   round.pos5
}

func columnSum(pos: Int) -> Int64 {
    switch pos {
    case 1: return coredata.reduce(0, { $0   $1.pos1 })
    case 2: return coredata.reduce(0, { $0   $1.pos2 })
    case 3: return coredata.reduce(0, { $0   $1.pos3 })
    case 4: return coredata.reduce(0, { $0   $1.pos4 })
    case 5: return coredata.reduce(0, { $0   $1.pos5 })
    default: return 0
    }
}

func columnAverage(pos: Int) -> Double {
    return Double(columnSum(pos: pos)) / Double(coredata.count)
}

Then you can do something like this in your view:

Text("Average row 1: \(columnAverage(pos: 1))")
  • Related