Swift Charts not importing into project correctly

50 Views Asked by At

I am trying to adopt Swift Charts but after adding it to my project and importing it in the file, I am still seeing warning messages in Xcode. I've read other threads and tried suggestions routes like clearing the cache, resetting Xcode, removing/re-adding the framework, etc. Nothing works.

import UIKit
import SwiftUI
import Charts


class MainQuickMenu: UIViewController {
    
    ... skipping IBOutlets, variables, lifecycle, etc...

    // First error thrown below "Cannot find type 'BarChartView' in scope"
    func createBarChart(data: [NSObject], containerView: UIView) -> BarChartView {
    let startDate = Calendar.current.date(byAdding: .day, value: -90, to: Date()) ?? Date()
    
    var dateCounts = [String: Int]()        
    for task in data {
        if let createdDate = task.value(forKey: "createdDate") as? Date, createdDate >= startDate {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd" // You can adjust the date format as needed
            let dateString = formatter.string(from: createdDate)
            dateCounts[dateString, default: 0] += 1
        }
    }
    
    let chartView = BarChartView()
    var dataEntries: [BarChartDataEntry] = []
    var index = 0
    ....

Tried so far:

  • I've tried with and without Charts.framework added to "Frameworks, libraries..."
  • I updated my entire project and code to conform to an iOS16 deployment target, as that's a requirement for Swift Charts.
  • I added SwiftUI to the file, even though the project is UIKit based, as I was willing to learn SwiftUI and adopt it for this view but still the errors persist.
  • I also tried importing SwiftUI and adding a standalone (outside of the class) struct using Chart components, to see if it was my class, but Chart classes still got errors.

Adding images below of configs as well.

Errors

enter image description here

Swift Charts Framework Imported

enter image description here

iOS16 deployment target

enter image description here

My goal here is just to understand how to begin to work with these Charts classes without the errors. Am I not importing Swift Charts correctly? To be clear, I'm not looking for an actual solution to the charts themselves.

1

There are 1 best solutions below

0
son On

I think you got it wrong.

  1. BarChartView is a component of Charts (DGChart). It's on this repo.
  2. As you mentioned above, you're trying to adapt the native Swift Charts. However, it also has the same name as DGChart by import Charts, that's why these errors show up.

BarChart in Swift Charts framework is something like:

Chart {
    BarMark(x: ..., y: ...)
}