Tuesday, May 10, 2016

How to call functions in a separate Swift file

Update - May 22, 2017. The code below still works with Xcode 8.3.1 (Swift 3.1).

The code below shows how to call functions in a separate Swift file. Xcode 7.3 (Swift 2.2) is used. Two examples are shown in the following steps:

1. Create a new Swift file with any name such as MyFile.swift.

2. Modify the file as:


import Foundation

//Example 1
class MyClass {
    func myFun() {
        print("myFun!!")
    }
    static let myInstance = MyClass()
}

//Example 2
class AnotherClass {
    class func anotherFun() {
        print("anotherFun!!")
    }
}

3. Modify ViewController.swift as:


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        MyClass.myInstance.myFun()
        
        AnotherClass.anotherFun()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Result of Debug Console:


myFun!!

anotherFun!!

No comments:

Post a Comment