LoginSignup
0
2

More than 3 years have passed since last update.

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

Last updated at Posted at 2021-05-29

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

画面収録-2021-05-29-22.26.14.gif

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
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2