skip to Main Content

I’m new to IOS Development and I’m unable to figure out how we can define a global method.
I have a function
func getBanners(){} declared in a class.
I want to declare and use it globally.

2

Answers


  1. you have several options here you could add it on global scope or introduce a class/enum with a static func. I personally would go with the enum, if functionality has to be available in another module, you have to set the access control to public.

    Cheers
    Sir SwiftAlot ✌️

    // on global scope
    func getBanners() -> [Banners] {
        return []
    }
    
    // class static func
    class Banners {
       static func get() -> [Banners] {
           return []
       }
    }
    
    // enum with static func
    enum Banners {
        static func get() -> [Banner] {
            return []
        }
    }
    
    Login or Signup to reply.
  2. If you have a function defined in a class

    class Foo
    {
        func bar() { ... }
    }
    

    provided you have an instance of the class, you can call it anywhere in the module:

    Foo()->bar()
    

    Note that Foo() creates an instance of Foo and then bar is called on that instance.

    If you want to be able to call the function without an instance, you need to mark it static:

    class Foo
    {
        static func bar() { ... }
    }
    

    To call it you need to specify the class:

    Foo.bar()
    

    Note that you can no longer access instance variables because the function is associated with the class itself, not a specific instance of the class.

    Also, it doesn’t need to be a class. You can also have static functions in enums and structs

    You can also have a bare function not declared in a class:

    func bar() { ... }
    

    Call it like this

    bar()
    

    The above is not generally considered good practice, although there are occasions where it is used in the Standard library e.g. print() and zip()

    To complicate things further, there are keywords to control the visibility of where you can call the function from

    private func alpha() { ... } // Visible only in the current source file
    internal func beta() { ... } // Visible only in the current module
    func gamma() { ... }         // default visibility is internal so visible in the current module
    public func delta() { ... } // visible anywhere in your program
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search