[iOS] How to make a Global function in Swift

Posted in :

You can create a custom class with the method you need like this:

class MyScene: SKScene {
    func CheckMusicMute() {
        if InGameMusicOnOff == true {
            SoundMute.texture = SKTexture(imageNamed: "SilverCircle.png")!
        }
        if InGameMusicOnOff == false {
            SoundMute.texture = SKTexture(imageNamed: "RedCircle.png")!
        }
    }
}

Then make GameScene extend MyScene:

class GameScene: MyScene

Well. In your GameViewController you have to transform your func in class func like this

class func yourFunc {
 //your code
}

To call it from your GameScene just this code :

GameViewController.yourFunc()

Don’t forget you are creating a global function so all variables in it have to be global too.

For you label (global):

var label:UILabel = UILabel()

in Your GameViewController:

class GameViewController : UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()

    label.text = "bonjour" // to set the text
    label.frame = CGRectMake(0, 0, 100, 100) / set the position AND size CGRectMake (x, y, width, heigth)

    label.textColor = UIColor.redColor() // set your color
    label.center = CGPointMake(self.view.frame.width/2, self.view.frame.height/2) // set the position from x=0 and y=0
    self.view.addSubview(label) // add the label to your screen

I hope it will help you.


Unless you declare the function as private or fileprivate, which limit the visibility to the file or scope where it is defined, you can use it anywhere in the module if declared as internal (the default), and also from external modules if declared as public or open.

However since you say that you need it in view controllers only, why not implementing it as an extension to the view controller?

extension UIViewController {
    func displayAlert(title:String, error:String, buttonText: String) {
        ...
    }
}

Almost every projects contains Utility Functions. With the introduction of Swift, there are multiple ways to write such functions.

Static Functions

Static functions are invoked by the class itself, not by an instance. This makes it simple to invoke utility functions without having to manage an object to do that work for you.

class AppUtils {
    static func appUtility() {
    }
}

We can access static function as AppUtils.appUtility()

Static functions can not be overridden.

Class Functions

Class functions (not instance methods) are also static functions but they are dynamically dispatched and can be overridden by subclasses unlike static functions.

class AppUtils{
    class func appUtility(){
        println("In AppUtils")
    }
}
class AppOtherUtils: AppUtils{
    override class func appUtility(){
        println("In AppOtherUtils")
    }
}

We can access them similar to static functions as AppUtils.appUtility() and AppOtherUtils.appUtility().

static is same as class final.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *