Exceptions
Exceptions

Reputation: 1204

Accessing method in another Swift file in AppDelegate

Here is my settings.swift file :

import Foundation

class Settings {

    func setDefaultSettings()  {
    }
}

I would like to access the function in AppDelegate didFinishLaunchingWithOptions. I've tried calling

Settings.setDefaultSettings() but it didn't work.

Upvotes: 2

Views: 1874

Answers (3)

Amit Singh
Amit Singh

Reputation: 2698

Method can be defined in two ways : Instance method and class Methods You have declared the method as Instance method, which can accessible through the instance of the class. So, to access the methods needs instance of the class, which can be created as

let settingObj = Settings()
settingObj.setDefaultSettings()

-------------------------------------------------

//Combined statement
Settings().setDefaultSettings()

and class method can be written using the keyword static or class. They can be access by the class name itself. Please see the example below

class Settings {

    class func setDefaultSettings()  
    {
        print("Default Settings")
    }
}

Now you can call the method directly by the class name

Settings.setDefaultSettings()

Upvotes: 1

Elena
Elena

Reputation: 829

You have two ways to make this work:

1.Initialise object of Settings class

Settings().setDefaultSettings()   

or

let settings = Settings()
settings.setDefaultSettings()

2.Make the function static

static func setDefaultSettings(){...}

in this case you can call it your way

Settings.setDefaultSettings()

Upvotes: 1

Hitesh Surani
Hitesh Surani

Reputation: 13557

You can access this method as follow

1) Create one Class of NSObject as follow.(GLOBAL.swift)

class GLOBAL : NSObject {

    //sharedInstance
    static let sharedInstance = GLOBAL()
}

2) Define your method here.

class GLOBAL : NSObject {

    //sharedInstance
    static let sharedInstance = GLOBAL()

    func setDefaultSettings()  {

    }
}

3) Use above method as follow.

GLOBAL.sharedInstance.setDefaultSettings()

You can also use this setDefaultSettings() in setting class and also any other class.

Upvotes: 0

Related Questions