user3069232
user3069232

Reputation: 8995

Closure Syntax with and without parameters

iOS 13, Swift 5

I am trying get my head around closure syntax in Swift and almost there. I got the first three bon, and understand them; but the last no. How do I call self.theMethod4 here? the syntax shown is wrong!

struct ContentView: View {
var body: some View {
    Text("Hello, World!")
      .onAppear {
        self.theMethod {
          print("1")
        }
        self.the2Method("Ya ") {
          print("1")
        }
        self.the3Method("Hello") {arg2do in
          print("1 ",arg2do)
        }
        self.the4Method("World") { (arg2do) -> String in
          print("1 ",arg2do)
        }
      }
}

func theMethod(_ endOfMethod: @escaping () -> Void) {
  print("2")
  endOfMethod()
}

func the2Method(_ arg1:String, endOfMethod: @escaping () -> Void) {
  print("3")
  endOfMethod()
}

func the3Method(_ arg1:String, endOfMethod: @escaping (_ arg2:String) -> Void) {
  print("4")
  endOfMethod("Yo")
}

func the4Method(_ arg1:String, endOfMethod: @escaping (_ arg2: String) -> String) {
  print("5")
  let an = endOfMethod("Pe")
  print("An ",an)
}
}

Upvotes: 1

Views: 668

Answers (2)

Sweeper
Sweeper

Reputation: 270820

You got the closure syntax ({ (parameters) -> ReturnValueType in statements }) right, but since the fourth method needs a closure that returns a String, you need to return a string.

For example, this:

self.the4Method("World") { (arg2do) -> String in
    print("1 ",arg2do)
    return "return value"
}

prints:

5
1  Pe
An  return value

Explanation of the output:

First the body of the4Method gets run, so 5 gets printed. Then the4Method calls endOfMethod, which is the closure passed in, with the argument "Pe". So print("1 ", "Pe") gets run, causing the second line to be printed. After that, the closure returns "return value" and we are now back to the4Method. The return value gets assigned to an, and print("An ",an) is run, causing the last line to be printed.

Upvotes: 2

Rob
Rob

Reputation: 437412

The closure in method 4 is defined to return a string, so when you call it, that’s what you’d have to do:

self.the4Method("World") { arg2do -> String in
    return "1 " + arg2do
}

Upvotes: 2

Related Questions