Home > Software design >  how to call a closure with argument in a function
how to call a closure with argument in a function

Time:02-19

func Test(clo: @escaping (String)->Void) 
{
  clo($0)
}

it return an error that says :

anonymous closure argument not contained in a closure

I want to be able to do:

Test{ n in 
var name = n
name = "Taha"
print(name)}

instead of hard coded String

func Test(clo: @escaping (String)->Void) 
{
  clo("Taha")
}

 

CodePudding user response:

That is not how closures work in Swift. And the code you wrote doesn't even make sense. Why do you assign n to name then change the value of name just to print it ?

The function with the closure will call the closure with a given value. You can think of closures as lambda functions. Here is an example:

func test(_ closure: @escaping (String) -> Void) {
    closure("My string")
}

test { str in
    print(str)  //prints " My string"
}

For what you are trying to achieve, just use a String parameter in your function:

func test(_ str: String) {
    print(str)
}

test("My string") // prints "My string"

Or use a closure that takes Void:

func test(_ closure: @escaping (Void) -> Void) {
    closure()
}

test { 
    print("My string") // prints "My string"
}

CodePudding user response:

It's:

func Test(clo: @escaping (Void)->Void) {
  clo()
}

And usage will be:

Test {
  print("Taha")
}
  • Related