Swift

Swift closure

eddie0329 2021. 11. 28. 21:05
λ°˜μ‘ν˜•

πŸ“Œ λͺ©λ‘

  • closure μ΄λž€?
  • ν΄λ‘œμ € κΈ°λ³Έ μ‚¬μš©
  • Example
  • parameter with closure
  • 닀쀑 인자 클둜져
  • 클둜져 κ°„μ†Œν™” ν•˜κΈ°

πŸ“Œ closure μ΄λž€?

μ½”λ“œμ—μ„œ 전달 및 μ‚¬μš©ν•  수 μžˆλŠ” 독립 κΈ°λŠ₯ 블둝이며, 일급 객체의 역할을 ν• μˆ˜ 있음

일급 κ°μ²΄λž€? 전달 인자둜 보낼 수 있고, λ³€μˆ˜/μƒμˆ˜ λ“±λ₯΄λ‘œ μ €μž₯ν•˜κ±°λ‚˜ 전달할 수 있으며, ν•¨μˆ˜μ˜ λ°˜ν™˜ 값이 λ μˆ˜λ„ μžˆλ‹€!

πŸ“Œ ν΄λ‘œμ € κΈ°λ³Έ μ‚¬μš©

{
  (λ§€κ°œλ³€μˆ˜) -> 리턴 νƒ€μž… in
  μ‹€ν–‰ ꡬ문
}

πŸ“Œ Example

let hello = { () -> () in
  print("Hello")
}

hello()

let hello2 = { (name: String) -> String in
  return "Hello, \(name)"
}

// hello2(name: "Eddie") -> ν•¨μˆ˜μ²˜λŸΌ label μ΄μžˆλŠ” ν˜•λŒ€λ‘œ 전달 ν•˜λ©΄ μ—λŸ¬
hello2("Eddie") // Hello, Eddie

πŸ“Œ parameter with closure

func doSomeThing(closure: () -> ()) {
  closure();
}

doSomeThing(closure: { () -> () in
  print("HELLO")
}) // hello

// λ§ˆμ§€λ§‰ 인자둜 closureκ°€ μ˜¨λ‹€λ©΄ 밖에 μ¨μ€„μˆ˜ μžˆμŠ΅λ‹ˆλ‹€.
doSomeThing() { () -> () in
  print("hello2")
}// hello2

// ν•˜λ‚˜λ§Œ λ°›λŠ”λ‹€λ©΄ ()도 μƒλž΅ κ°€λŠ₯!
doSomeThing { () -> () in
  print("hello2")
}// hello2

// λ¦¬ν„΄μœΌλ‘œ ν΄λ‘œμ €
func doSomeThing2() -> () -> () {
  return { () -> () in
    print("HELLO4")
  }
}

doSomeThing2() // HELLO4

πŸ“Œ 닀쀑 인자 클둜져

func temp(success: () -> (), fail: () -> ()) {
  success()
  fail()
}

temp {
  () -> () in
  print("success")
} fail: {
  () -> () in
  print("fail")
}
// success, fail

πŸ“Œ 클둜져 κ°„μ†Œν™”ν•˜κΈ°

func temp2(closure: (Int, Int, Int) -> Int) {
  closure(1, 2, 3)
}

// νƒ€μž… 좔둠을 μ΄μš©ν•΄ 리턴 νƒ€μž…λ„ μƒλž΅ κ°€λŠ₯ ν•˜λ‹€
temp2(closure: { (a, b, c) in
  return a + b + c
})

// $0...으둜 인자 값을 μ°Έκ³  ν• μˆ˜ μžˆλ‹€
temp2(closure: {
  return $0 + $1 + $2
})

// return을 μƒλž΅κ°€λŠ₯
temp2(closure: {
  // print("hello") 단일 리턴문이 μ•„λ‹ˆλ©΄ μ—λŸ¬ λ°œμƒ
  $0 + $1 + $2
})

// λ°–μœΌλ‘œ λΊ΄λ‚Όμˆ˜ μžˆλ‹€
temp2() {
  $0 + $1 + $2
}

// μΈμžκ°€ ν•˜λ‚˜λΌλ©΄ ()도 μƒλž΅ κ°€λŠ₯
temp2 {
  $0 + $1 + $2
}
λ°˜μ‘ν˜•