Fortun Fortun - 2 months ago 6
Swift Question

Calling function from a class

I am trying to become confident using functions. I am practicing with the code below.

class Arithmetics {
var operand1: Double
var operand2: Double

init(operand1: Double, operand2: Double) {
self.operand1 = operand1
self.operand2 = operand2
}
func AddInsideClass(operand1: Double, operand2: Double) -> Double {
var sum = operand1 + operand2
return sum
}
}

func AddOutsideClass(operand1: Double, operand2: Double) -> Double {
var sum = operand1 + operand2
return sum
}

println(AddOutsideClass(5.5, 4.5))
println(Arithmetics.AddInsideClass(5.5, 4.5))


In the last 2 lines I tried to call the functions and output them on the console. The first println() is calling the function from outside the class, which works fine.
The second println() however gives me an error message that goes like this:

"stdin:23:35: error: extra argument in call
println(Arithmetics.AddInsideClass(5.5, 4.5))
^ ~~~"

What's the problem here?

Is it because I cannot simply call a class method directly? Or can I call class methods only via a class instance like below?

var operation1: Double = Arithmetics.AddInsideClass(5.5, 4.5)

Answer

You have two options:

First – using your syntax – you declare the function as static and you can omit the variables and the init function

class Arithmetics {

  static func addInsideClass(operand1: Double, operand2: Double) -> Double {
    var sum = operand1 + operand2
    return sum
  }
}

You can call it on the class (the second parameter name is mandatory)

Arithmetics.addInsideClass(5.5, operand2:4.5)

Second you create an instance of the class which now needs no operands in the add function because they are set in the init function.

class Arithmetics {
  var operand1: Double
  var operand2: Double

  init(operand1: Double, operand2: Double) {
    self.operand1 = operand1
    self.operand2 = operand2
    }

  func addInsideClass() -> Double {
    var sum = operand1 + operand2
    return sum
    }
}

And the syntax to call it is

let operation1 = Arithmetics(operand1: 5.5, operand2: 4.5)
operation1.addInsideClass()
Comments