Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print a function inside class

Pretty dumb question, but i really don’t know how to solve this problem of mine.

For example, to print() the result of a function i do:

func abc(a: Int, b:Int) -> Int { 
    return a+b 
} 
print(abc(a:1,b:1))

And that’s my question, how to print() the result of a function inside class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Solution {
    func abc(a: Int, b:Int) -> Int {
       return a+b
    }
}

Tried to do the same – error, also idk how to google it, i tried but got nothing

>Solution :

In your second snippet, the function abc(a:b:) is inside your Solution class textually, but conceptually, it belongs to instances ("objects") of the class. These kinds of functions are often called "methods", or "member functions".

So to call it, you first need to create ("instantiate") an object of that class. In Swift, objects are instanciated by calling an initializer, like so:

let aNewObjectOfSolution = Solution() // Solution() shorthand for Solution.init()

You can then call abc on that object, something like:

let aNewObjectOfSolution = Solution()
let result = aNewObjectOfSolution.abc(a: 1, b: 1)
print(result)

Or inlined:

print(Solution().abc(a: 1, b: 1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading