Having Trouble executing function but not for loop it is in

EQOxx123

I am trying to create a function that can take in a function and an Int(numberOfTimes) and then call on doFunctionXTimes() a certain number of times. However, it only prints out "Hello Ethan" once opposed to five times. Here is my code:

func doFunctionXTimes(numberOfTimes: Int,function: Any) {
    for _ in 1...numberOfTimes {
       function
    }
}
func sayHello(name: String) {
    print("Hello \(name)")
}

doFunctionXTimes(5, function: sayHello("Ethan"))

//this code prints "Hello Ethan"

However, if change _ to i in the for loop in doFunctionXTimes() and then add a print(i) statement either above or below where I call the function, it will print out all of the numbers from 1 to 5. How can I make it so the function is called on as many times as the print(i) statement is called on and printed. Thank you. Here is my edited code printing i.

func doFunctionXTimes(numberOfTimes: Int,function: Any) {
    for i in 1...numberOfTimes {
        print(i)
       function
        // or the print(i) statement can here. It does not affect the output.
    }
}
func sayHello(name: String) {
    print("Hello \(name)")
}

doFunctionXTimes(5, function: sayHello("Ethan"))

// this code prints out "Hello Ethan" and then 1 2 3 4 5

Any help or advice is great and I hope this helps future viewers.

Michael

Have a look at the following code:

doFunctionXTimes(5, function: sayHello("Ethan"))

The sayHello("Ethan") part is a function call. So when the line of code runs, it first calls this function - before entering doFunctionXTimes. Then inside your code, you have:

function

This doesn't actually call the function (it's similar to putting 0 on a line by itself). To achieve what you want, you need a closure, which will "wrap around" the function that you want to call:

func doFunctionXTimes(numberOfTimes: Int,function: (() -> Void)) {
    for _ in 1...numberOfTimes {
       function()
    }
}
func sayHello(name: String) {
    print("Hello \(name)")
}

doFunctionXTimes(5, function: { sayHello("Ethan") })

Now function is passed as { sayHello("Ethan") }, and sayHello won't be called until the function is called.

Note that function is now defined as () -> Void, which means it's a func that takes no parameters and returns no value. (I put extra braces around the definition because I find it improves clarity)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive