Home > front end >  How to print a function inside class
How to print a function inside class

Time:12-17

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:

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

CodePudding user response:

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))
  • Related