Thanks a lot for the reply. It's true that I am learning to write closures at this stage. Actually I read somewhere about the "forEach" function that works on collections and that takes a single argument as parameter (i.e a closure).
Syntax of forEach is "Void forEach(body: (Int) throws -> Void) rethrows"
What I am trying to do is write a similar function with a single parameter (i.e a closure) that will calculate the Factorial of a number and so we can print the Factorial of that number. I don't want to pass that number as a second parameter to that function.
I understand that forEach is a member function of Collections class that works on each element one by one. So it picks up the elements from within the array. Similarly I have created a private property (factorialNumber) inside my class (whose value I can set using the public function "setFactorialNumber"). Now I am trying to create a public function (factorial) for my class that will have only one parameter (i.e the closure) that will use the value of "factorialNumber" property internally and calculate the factorial of that number that we can print from outside when we call that function from the other code.
Below is my class..
public class MyArray {
private var factorialNumber = 0
public func setFactorialNumber(factorialNumber value: Int) {
factorialNumber = value
}
public func factorial(body closure: (Int) -> Void) -> Void {
var outputString: String?
var result = 1
if factorialNumber <= 0 {
outputString = nil
} else {
outputString = ""
while(factorialNumber >= 1) {
if factorialNumber == 1 {
outputString = outputString! + "\(factorialNumber) = \(result)"
break
} else {
outputString = outputString! + "\(factorialNumber) x "
}
result = result * factorialNumber
factorialNumber -= 1
}
}
}
}