Closure๋?
์ผ์ ๊ธฐ๋ฅ์ ํ๋ ์ฝ๋๋ฅผ ํ๋์ ๋ธ๋ก์ผ๋ก ๋ชจ์๋์ ๊ฒ.
func ํค์๋๋ฅผ ์ฌ์ฉํ์ฌ ๋ง๋ค์๋ ํจ์๋ named closure๋ผ๊ณ ํ๋ค.
- ์ด๋ค ์์๋ ๋ณ์์ ์ฐธ์กฐ๋ฅผ ์บก์ณํด ์ ์ฅํ ์ ์๋ค.
- ํด๋ก์ ๋ฅผ ๋ณ์๋ ์์์ ๋์ ํ ์ ์๋ค.
- ํจ์์ ํ๋ผ๋ฏธํฐ๋ก ํด๋ก์ ๋ฅผ ์ ๋ฌํ ์ ์๋ค.
- ํจ์์ ๋ฐํ ํ์ ์ผ๋ก ํด๋ก์ ๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
ํด๋ก์ ํํ ๋ฌธ๋ฒ (Closure Expression Syntax)
{ (parameters) -> return type in
statements
}
- ์ ) ๋ฐฐ์ด ์ ๋ ฌ ์ฝ๋
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
}
์๋ ๋ฐฉ์
ํ๋ฉด1์์ ์ฅ๋ฐ๊ตฌ๋ํด๋ฆญ -> ํ๋ฉด2์์ ์ํ์ ํ -> ํ๋ฉด1์์ ์ํ์ ๊ฐ์๋ฅผ ๋์ฐ๋ alert์ฐฝ
- ๋ฐ์ดํฐ ์์ฒญ์ ๋ฐ์ Received View Controller์์ Closure ์ ์ธ
์์ดํ ๊ฐ์๋ฅผ ์ ๋ฌํด์ฃผ๋๊น Int -> Void ํํ๋ก ์ ์ธ
var closure: ((Int) -> ())? // ํด๋ก์ ์ ์ธ
- ์ฅ๋ฐ๊ตฌ๋ ๋ด๊ธฐ ๋ฒํผ์ ํด๋ฆญํ์๋
ํด๋ก์ ๋ฅผ ์คํํ๋ฉด์ ์ฅ๋ฐ๊ตฌ๋์ ๋ช๊ฐ๊ฐ ๋ด๊ฒผ๋์ง ํ๋ผ๋ฏธํฐ๋ก ์ ๋ฌํด์ค๋ค.
@IBAction func insertCartButtonTapped(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
closure?(itemCount)
}
- ์นดํธ ๋ฒํผ ํด๋ฆญํ์ ๋ ํด๋ก์ ๋ฅผ ์คํํด์ค๋ค
๋ฒํผ์ด ๋๋ฆฌ๋ฉด closure๊ฐ ์คํ๋๋๋ก!
๋๋ฒ์งธ ๋ทฐ์ปจํธ๋กค๋ฌ(Received ViewController) ๊ฐ dismiss๋๊ณ closure?๋ฅผ ํธ์ถํ๋ฉด ์ฒซ๋ฒ์งธ ๋ทฐ์ปจํธ๋กค๋ฌ( Send View Controller )์ clousre๋ฅผ ์คํํด์ค๋ค.
@IBAction func cartButtonTapped() {
let cartVC = storyboard?.instantiateViewController(identifier: "ReceiveViewController") as! ReceiveViewController
cartVC.closure = { itemCount in
let alertVC = UIAlertController(title: "์ฅ๋ฐ๊ตฌ๋ ํ์ธ", message: "์ฅ๋ฐ๊ตฌ๋์ \(itemCount)๊ฐ์ ์ํ์ด ์ถ๊ฐ๋์์ต๋๋ค.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "ํ์ธ", style: .default, handler: nil)
alertVC.addAction(okAction)
self.present(alertVC, animated: true, completion: nil)
}
if let productName = productNameLabel.text,
let price = priceLabel.text {
cartVC.productName = productName
cartVC.price = price
}
present(cartVC, animated: true, completion: nil)
}
์ถ์ฒ
SOPT 7์ฃผ์ฐจ ์ธ๋ฏธ๋