[Swift] Closure and Trailing closure

Closure

  • Closure is independent code block
func add(x: Int, y: Int) -> Int {
  return(x + y)
}

print(add(x: 10, y: 20))// 30


// closure
let add1 = { (x: Int, y: Int) -> Int in 
  return(x + y)
}
print(add1(10, 20)) // 30

func mul(val1: Int, val2: Int) -> Int {
  return val1 * val2;
}
print(mul(val1:10, val2:20))

//closure
let multiply = {(val1: Int, val2: Int) -> Int in 
  return val1 * val2
}
print(multiply(10, 20))

Trailing closure

  • If closure is the last argument of a function, omit the last parameter handler: and implement closure outside the function square brackets
let onAction = UIAlertAction(title: "On.", style: UIAlertAction.Style.default) {
  ACTION in self.lampTmg.image = self.imgOnslef.isLampOn = true
}

let removeAction = UIAlertAction(title: "Off.", style: UIAlertAction.Style.destructive, handler: {
  ACTION in self.lampImg.image = self.imgRemoveself.isLampOn = false
})

Reference