ํด๋ก์ (Closure)๋?
์ฝ๋์์ ์ ๋ฌ๋๊ณ ์ฌ์ฉ๋ ์ ์๋ ์์ฒด์ ์ธ(self - contained)ํจ์ ๋ธ๋ก
- ๋๋ค ํจ์์ ์ ์ฌ
- ํด๋์ค์ ๋์ผํ ์ฐธ์กฐ ํ์
๊ธฐ์กด ํจ์์ ํด๋ก์ ํจ์ ๋น๊ต
func aFunction(str: String) -> String {
return "Hello, \(str)"
}
let _ = {(str: String) -> String in
return "Hello, \(str)"
}
ํด๋ก์ ํจ์ ํํ
{ (๋งค๊ฐ๋ณ์ ๋ชฉ๋ก) -> ๋ฐํ ํ์
in
์คํ ์ฝ๋
}
ex) a์ b๋ฅผ ๋ํ๋ ํจ์
let _ = {(a: Int, b: Int) -> Int in
let result = a + b
return result
}
ํด๋ก์ (Closure) ์๋ต
- ๋ฐํ, ์ธ์ ํ์
์๋ต
ํ์
์ ์๋ ๊ฒฝ์ฐ ํ์
์๋ต ๊ฐ๋ฅ
let closure1 = {a, b in
let result = a + b
return result
}
- ๋ฐํ ํค์๋ ์๋ต
๋จ์ผ ํํ ํด๋ก์ ๋ ๋ฐํ ํค์๋ ์๋ต ๊ฐ๋ฅ
let closure2: (Int, Int) -> Int = { a, b in
a + b
}
- ์ธ์ ์ด๋ฆ ์ถ์ฝ (Shorthand Arguments Names)
ํด๋ก์ ์ ๋งค๊ฐ๋ณ์ ์ด๋ฆ์ด ๊ตณ์ด ํ์ ์๋ค๋ฉด ๋จ์ถ ์ธ์๋ฅผ ํ์ฉ ๊ฐ๋ฅํ๋ค.
let closure3: (Int, Int) -> Int = { $0 + $1 }
- ์ฐ์ฐ์ ๋ฉ์๋(Operator Methods)
let closure4: (Int, Int) -> Int = (+)