Alec O'Connor
Alec O'Connor

Reputation: 265

Breaking swift program into multiple files

Surprisingly, I'm having trouble searching for this. How do I place assisting classes in separate files in Swift? If I want to store an addition function in a separate math class in the same file, I can call math.add(), but if I want to store the class and function it in a math.swift file and reference it from the main file, what would I use?

Upvotes: 3

Views: 4753

Answers (1)

Dan Beaulieu
Dan Beaulieu

Reputation: 19954

If you're simply looking to make a new file with your class and call it from main (or viewDidLoad). You can do the following.

  • Just make a new file by right clicking on your desired folder and choosing new file.
  • Choose a simple Swift file and name it Math.swift and create.
  • Copy your math class into the file, it'll wind up looking something like this.

Math.swift

import UIKit

class Math {

    func add(param:Int, param: Int) {
        //... your implementation
    }
}

Then in main (or viewDidLoad) create an instance of your math class:

var myMathClass = Math()

then call your function:

myMathClass.add(5, 5) // you've called your function

There are quite a few different options. If you share some code and clarify your question I can help you better.

Upvotes: 2

Related Questions