Nested function with Core Data

Viewed 42

SwiftUI newbie here :-)

I have a Core Data entity, "Cars", with the following attributes:

    @NSManaged public var id: UUID?
    @NSManaged public var uses: Int16
    @NSManaged public var cost: Int16
    @NSManaged public var type: String

I'm trying to print out the average cost per use for each type of car (by which I mean, for example, how many times all VWs was used, divided by total cost of all VWs, divided by total count of VWs).

I've managed to group the cars into types with the function group:

func group(_ result : FetchedResults<Cars>)-> [[Cars]] {
        
    return Dictionary(grouping: result) { $0.type }
            .sorted(by: {$0.key < $1.key})
            .map {$0.value}
        
    }

However, now I'm struggling to create an array which holds the average for each type.

I've tried adding this function, but get the message "Cannot find 'av' in scope":

func andAv (cars: [[Cars]]) -> [Int] {
    
    
    ForEach(cars, id: \.self) { i in
        
        let sumCost = i.map { Int($0.cost) }.reduce(0,+)
        let sumUses = i.map { Int($0.uses) }.reduce(0,+)
        let itemCount = i.map { $0.id }.count
        let av = sumCost / sumUses / itemCount
    }
    
    return [av]
    
}

I think maybe I need to be using a nested function?

As I mention, I'm a beginner and SwiftUI is my first programming language, so perhaps I'm missing something very obvious or making a silly mistake. In either case, any help hugely appreciated!

1 Answers

ForEach is a SwiftUI type which is for creating views based on a collection of data. You're not interested in views at this point.

func andAv (cars: [[Cars]]) -> [Int] {
    
    let averages: [Int] = cars.map { i in
        
        let sumCost = i.map { Int($0.cost) }.reduce(0,+)
        let sumUses = i.map { Int($0.uses) }.reduce(0,+)
        let itemCount = i.count
        let av = sumCost / sumUses / itemCount
        return av
    }
    
    return averages
    
}

You should also address the points in vadian's answer regarding integers and Core Data types, but your fundamental problem is that ForEach is for building views, not for processing data.

Related