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
}
λ°μν