Home Difference between calling a method inside and outside a class
Reply: 0

Difference between calling a method inside and outside a class

Ryoko
1#
Ryoko Published in 2018-01-11 03:32:37Z

Is there any practical difference between declaring a function inside a class or outside of it?

(I'm a beginner in swift)

Context: I noticed I can declare a function outside a class (in a .swift file) and calling it (in a different .swift file) without the need to instantiate or initialize something before using it. But as I was learning more, I found there are two additional ways to declare a function.

Case 1: FreeMethod.swift (no need to embed it into a class)

import Foundation

func alpha (a: Int, b: Int) {
    let c = a + b
    print(c)
}

Case 2: ClassWithInit.swift (instantiate the class within it)

import Foundation

class ClassWithInit {
static let helper = ClassWithInit()
func alpha (a: Int, b: Int) {
    let c = a + b
    print(c)
}
}

Case 3: ClassAndStaticFunc.swift (declaring the method as 'static')

import Foundation

class ClassAndStaticFunc {

static func alpha (a: Int, b: Int) {
    let c = a + b
    print(c)
}
}

I know there are several differences of syntax when its time to call ‘alpha’ depending on which way I chose to declare it. But, beyond the different syntax used to call it, what is the difference of declaring and using it in each case?


What I have read/learn so far:

Declaring the function inside a class allows me to inherit methods of other superclasses or delegates. But I feel there’s more than that. I read that declaring it as a static method (case 3) instantiate alpha just one time and whether is called 1 or 1000 times it will be always the same instance. (I suspect it affects something related to memory handling)


Lectures, videos, tutorials or other sources or information to learn about this are welcome :)

Thank you

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.29967 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO