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?
-
I found a post that mentions using handlers, but it is not clear on their exact use, how they are used, or if other methods are available.– Alec O'ConnorJan 19, 2016 at 21:59
-
add an example of your math functions and the context you'd like to use them in.– Dan BeaulieuJan 19, 2016 at 22:26
-
Are you asking how to create files and new classes?– tskulbruJan 19, 2016 at 22:27
1 Answer
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.
-
how create main class ? or how create the viewDidLoad– user7396942Aug 21, 2019 at 19:00
-
@x-rw are you trying to make a class with the ViewDidLoad override? Aug 21, 2019 at 19:30