コールバック関数(クロージャ)を使用した値渡しのサンプルを作成してみた


クロージャー、コールバック関数について理解を深めるためにサンプルを作ってみました。
この書き方があっているのか分かりませんが、とりあえず動いたので。

FirstViewController.swift
import UIKit

class FirstViewController: UIViewController {


    @IBOutlet weak var label: UILabel!{
        didSet{
            label.text = "0"

        }
    }


    @IBAction func nextButton(_ sender: UIButton) {

            let secondStoryboard = UIStoryboard(name: "Second", bundle: nil)
            let secondVC = secondStoryboard.instantiateInitialViewController() as!SecondViewController


        secondVC.completion = { CountModel in
            print("ーーーー渡されたよーーーーーーー")
            self.label.text = CountModel.count.description
    }

        let nav = self.navigationController!
        nav.pushViewController(secondVC, animated: true)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

 }

}
SecondViewController.swift
import UIKit

class SecondViewController: UIViewController{


   private var countmodel = CountModel.init(count: 0)
    var completion:((CountModel)->Void)?

    @IBOutlet weak var countLabel: UILabel!{
        didSet{
            countLabel.text = countmodel.count.description
        }
    }

    @IBAction func countButtun(_ sender: UIButton) {
        countmodel.count = countmodel.count + 1
        countLabel.text = countmodel.count.description
        print(countmodel)
    }


    @IBAction func addButton(_ sender: Any) {
        tap()
        self.navigationController?.popViewController(animated: true)

    }

    //クロージャー関数
    func tap(){
        print("tapしたよ")
        print(countmodel)
       completion?(countmodel)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        }


    }
CountModel.swift
import Foundation

struct CountModel {
    var count:Int
}