Ad

How To Call A Closure With Argument In A Function

- 1 answer

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")
}

 
Ad

Answer

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"
}
Ad
source: stackoverflow.com
Ad