1

I'm new in Swift and CoreData and I have a question on how to read data that was stored in CoreData (NsManagedObject) and save it to an data array which can than be used as input for a SwiftUI Line Chart.

My test data model is simple:

@NSManaged public var date: Date?
@NSManaged public var value: Double

I'm able to read the number of values by using this code:

private func fetchItem() {
        withAnimation {
            let fetchRequest: NSFetchRequest<Rate> = Rate.fetchRequest()
            do {
                let fetchedResults = try viewContext.fetch(fetchRequest)
                print("#Entities: \(fetchedResults.count)")
                
            } catch {
                print(error)
              }
        }
    }

Now I need the double values from Core Data stored in an array. For the Line Chart demo (iLineChart) I have the following test data array:

let data = (1...100).map( {_ in Double.random(in: -1...10)} )

Question:

How can I create an array with double values from the NSManagedObject values?

Regards, Ralf

1 Answer 1

5

You want to convert an array of Rate (ie [Rate]) into an Array of Double (ie Double), where it will be filled with the value of each Rate.

That's a job for map()! It does exactly that: iterate over the initial array, for each element (here a Rate element) return what you want to extract from it (here just its property value).

Quick answer and "Swifty" one:

let data = fetchedResult.map { $0.value }

More explicit:

let data = fetchedResult.map { aRate in 
    return aRate.value
}

Manually done:

var data: Double = []
for aRate in fetchedResults { 
    data.append(aRate.value)
}

Note: The map is Swifty, in oneline, BUT no one should criticize the use of the manuel for loop. That's basic algorithm, and understanding them is a solid foundation on how to develop. So if it's still your level of knowledge, I'd recommend to use the for loop. Because if you need to change the output/result of the map, will you be able to do so? Let's say the value + an offset of 30 on the value, and all in absolute values?

Sign up to request clarification or add additional context in comments.

1 Comment

THANKS a lot - you saved my day. I have used the for loop and it works as described. Have a nice day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.