DEV Community

Saurabh Chavan
Saurabh Chavan

Posted on • Updated on

Day 6 : 100DaysOfSwift🚀

Day 6

Closures Part 1

In Swift, a closure is a special type of function without the function name

Example

let Sau = {
    print("I'm Saurabh, iOS developer")
}

//call the Closure
Sau()
Enter fullscreen mode Exit fullscreen mode

2.Closure with Parameter

We don't use the func keyword to create closure. Here's the syntax to declare a closure:

{ (parameters) -> returnType in
   // statements
}
Here,
Enter fullscreen mode Exit fullscreen mode

parameters - any value passed to closure
returnType - specifies the type of value returned by the closure
in (optional) - used to separate parameters/returnType from closure body

Example

let Sau={ (name:String) in
print("MySelf \(name)")
}

//Call the Closure
Sau("Saurabh")
Enter fullscreen mode Exit fullscreen mode

return value in Closure

If we want our closure to return some value, we need to mention it's return type and use the return statement. For example,

/ closure definition
var findSquare = { (num: Int) -> (Int) in
  var square = num * num
  return square
}

// closure call
var result = findSquare(3)

print("Square:",result)
Enter fullscreen mode Exit fullscreen mode

Closure as parameter

closures can be used just like strings and integers, you can pass them into functions.

let driving = {
    print("I'm driving in my car")
}

func travel(action: () -> Void) {
    print("I'm getting ready to go.")
    action()
    print("I arrived!")
}

travel(action: driving)
Enter fullscreen mode Exit fullscreen mode

If we wanted to pass that closure into a function so it can be run inside that function, we would specify the parameter type as () -> Void. That means “accepts no parameters, and returns Void” – Swift’s way of saying “nothing”.

Top comments (0)