mx1txm
mx1txm

Reputation: 139

How to use functions from other swift files (same target) in same project

Hey I have 2 Classes each in own swift file. Im basically doing this only to get a better overview in my Viewcontroller. Still, I need to get access to the data or call the func from other files in my view controller.swift file. Its in the same Target so I don't need to import it in my view controller file right?

If I do override the func viewDidLoad() I get an Exception so I guess I am only allowed to do it once (-> in my viewController.swift)

//ViewController.swift

class ViewController: UIViewController{


    @IBOutlet weak var xMotion: UILabel!
    @IBOutlet weak var yMotion: UILabel!
    @IBOutlet weak var zMotion: UILabel!

    @IBOutlet weak var lineChartView: LineChartView!
    @IBOutlet weak var lineChartView2: LineChartView!


override func viewDidLoad() {
    super.viewDidLoad()

       timebuffer.append(Double(ts1))
       colors.append(UIColor.red)

       Graphen.customizeChart(values: buffer1.map { Double($0) })
       Graphen.filteredChart(values: buffer2.map { Double($0) })
       Graphen.multipleCharts()
}

//Graphen.swift

class Graphen : ViewController
{

    //creates Plot with specific numbers/data
    func customizeChart(values: [Double]){
        var dataEntries: [ChartDataEntry] = []
        for i in 0..<buffer1.count{//dataPoints.count
            let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
            dataEntries.append(dataEntry) }
        lineChartDataSet = LineChartDataSet(entries: dataEntries, label: nil)
        lineChartDataSet.circleRadius = 0.5
        let lineChartData = LineChartData(dataSet: lineChartDataSet)
        self.lineChartView.data = lineChartData
    }
}

Upvotes: 0

Views: 228

Answers (1)

PGDev
PGDev

Reputation: 24341

viewDidLoad() is a lifecycle method of a UIViewController's instance. Thus, it can be overridden in each UIViewCiontroller subclass, i.e.

class ViewController: UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        //your code here...
    }
}


class Graphen : ViewController
{
    override func viewDidLoad() {
        super.viewDidLoad()
        //your code here...
    }
}

Now, you don't need to import any file/class as long as they are in the same target.

Now, since Graphen's customizeChart(values:) method is an instance method, so you need to create an instance of Graphen first and then use it to call its instance methods like so,

let graphen = Graphen()
graphen.customizeChart(values: buffer1.map { Double($0) })

Similarly call other instance methods of Graphen. Assuming that filteredChart(values:) and multipleCharts() are also instance methods, you can invoke them like,

graphen.filteredChart(values: buffer2.map { Double($0) })
graphen.multipleCharts()

Upvotes: 1

Related Questions